我有一个包含2个文本字段的数据框:评论和主要帖子
基本上这是结构
id comment post_text
1 "I think that blabla.." "Why is blabla.."
2 "Well, you should blabla.." "okay, blabla.."
3 ...
我想计算第一行中的注释文本与第一行中的post_text中的文本之间的相似度,并对所有行执行此操作。 据我所知,我必须为两种类型的文本创建单独的dfm对象
corp1 <- corpus(r , text_field= "comment")
corp2 <- corpus(r , text_field= "post_text")
dfm1 <- dfm(corp1)
dfm2 <- dfm(corp2)
最后,我想获得如下内容:
id comment post_text similarity
1 "I think that blabla.." "Why is blabla.." *similarity between comment1 and post_text1
2 "Well, you should blabla.." "okay, blabla.." *similarity between comment2 and post_text2
3 ...
我不确定如何继续,我在StackOverflow上找到了这个 Pairwise Distance between documents 但是它们正在计算dfm之间的互相似性,而我需要逐行进行相似性
所以基本上我想做的是:
dtm <- rbind(dfm(corp1), dfm(corp2))
d2 <- textstat_simil(dtm, method = "cosine", diag = TRUE)
matrixsim<- as.matrix(d2)[docnames(corp1), docnames(corp2)]
diagonale <- diag(matrixsim)
但是对角线只是1 1 1 1的列表。
关于如何解决此问题的任何想法? 预先感谢您的帮助,
卡洛
答案 0 :(得分:1)
我会通过创建单列文档来做到这一点,但是使用表示文档类型的文档名来区分它们。
df <- data.frame(
id = c(1, 2),
comment = c(
"I think that blabla..",
"Well, you should blabla"
),
post_text = c(
"Why is blabla",
"okay, blabla"
),
stringsAsFactors = FALSE
)
# stack these into a single "document" column, plus a docvar
# identifying the document type
df <- tidyr::gather(df, "source", "text", -id)
df
## id source text
## 1 1 comment I think that blabla..
## 2 2 comment Well, you should blabla
## 3 1 post_text Why is blabla
## 4 2 post_text okay, blabla
library("quanteda")
## Package version: 1.4.3
## Parallel computing: 2 of 12 threads used.
## See https://quanteda.io for tutorials and examples.
##
## Attaching package: 'quanteda'
## The following object is masked from 'package:utils':
##
## View
corp <- corpus(df)
docnames(corp) <- paste(df$id, df$source, sep = "_")
dfm(corp) %>%
textstat_simil()
## 1_comment 2_comment 1_post_text
## 2_comment -0.39279220
## 1_post_text -0.14907120 -0.09759001
## 2_post_text -0.14907120 0.29277002 0.11111111
您现在可以使用矩阵子设置切出所需内容。 (使用as.matrix()
将textstat_simil()
的输出转换为矩阵。)