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

Compare the words from a data frame and calculate a matrix with the length of the biggest word for each pair

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

为了更全面,让我们考虑以下示例。

test <- c("hello", "hi", "play", "kid") 

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

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

       hello  hi play kid
 hello  5     5   5    5

  hi    5     2   4    3

 play   5     4   4    4

  kid   5     3   4    3

如何在 R 中实现?

你可以这样做:

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

或更短,如@Ronak Shah 所建议

outer(nchar(test), nchar(test), pmax)

另一个选项 expand.grid 可以是,

matrix(do.call(pmax, expand.grid(nchar(test), nchar(test))), nrow = length(test))

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

您也可以使用 sapply:

mat <- sapply(test, function(x) pmax(nchar(x), nchar(test)))
rownames(mat) <- colnames(mat)
mat
      hello hi play kid
hello     5  5    5   5
hi        5  2    4   3
play      5  4    4   4
kid       5  3    4   3