比较数据框中的单词,并计算每对最大单词长度的矩阵

zer*_*ero 4 r distance matrix text-mining dataframe

我有一个包含许多唯一单词的数据框。我想在R中创建代码,其中每个单词都将与所有单词进行比较,并创建一个矩阵,其中每个单词对的最大单词的长度。

为了更全面,请考虑以下示例。

test <- c("hello", "hi", "play", "kid") 
Run Code Online (Sandbox Code Playgroud)

我想创建一个矩阵来比较测试中的每个单词,并给出最大单词的长度。

对于前面的示例,我想采用以下矩阵:

       hello  hi play kid
 hello  5     5   5    5

  hi    5     2   4    3

 play   5     4   4    4

  kid   5     3   4    3
Run Code Online (Sandbox Code Playgroud)

我如何在R中做到这一点?

Hum*_*hen 6

你可以这样做:

outer(test, test, function(x,y) pmax(nchar(x), nchar(y)))

     [,1] [,2] [,3] [,4]
[1,]    5    5    5    5
[2,]    5    2    4    3
[3,]    5    4    4    4
[4,]    5    3    4    3

Run Code Online (Sandbox Code Playgroud)

甚至更短,如@Ronak Shah所建议

outer(nchar(test), nchar(test), pmax)
Run Code Online (Sandbox Code Playgroud)