与 R 的文本相关性

Text correlation with R

我正在使用一个 DF,其中包含多行文本 ID、文本语料库和所述语料库中的单词数。它看起来像这样:

    ID                        Text     W_Count
Text_1         I love green apples           4
Text_2    I love yellow submarines           4
Text_3 Remember to buy some apples           5
Text_4               No match here           3

有了那个 DF,我想计算所有行彼此共有的单词数。例如 Text_1Text_2 有两个相同的词,而 Text_1Text_3 只有一个。

完成后,我需要在类似于此的矩阵中显示数据:

      ID Text_1 Text_2 Text_3 Text_4
Text_1      4      2      1      0
Text_2      2      4      0      0
Text_3      1      0      5      0
Text_4      0      0      0      3

我设法只用两行来做到这一点,例如 Text_1Text_2:

Text_1 = df[1, 2]
Text_2 = df[2, 2]
Text_1_split <- unlist(strsplit(Text_1, split =" "))
Text_2_split <- unlist(strsplit(Text_2, split =" "))
count = length(intersect(Text_1_split, Text_2_split))
count
[1] 2

但我不知道如何对所有行系统地应用它,然后显示我需要的矩阵。

非常感谢任何帮助。

您可能正在寻找 vapply 函数。考虑以下因素:

vapply(df$ID, 
           function(x){
                sapply(df$ID, 
                       function(y){
                          x_split <- unlist(strsplit(df$Text[df$ID == x], split = " "))
                          y_split <- unlist(strsplit(df$Text[df$ID == y], split = " "))

                          return(length(intersect(x_split, y_split)))
                       })
            }, 
           integer(nrow(df)))

vapply 函数 ("vector-apply") 将函数应用于一系列输入,returns 以其第三个参数形式的向量(在本例中为整数长度等于您的数据输入的长度。