【问题标题】:Compare the words from a data frame and calculate a matrix with the length of the biggest word for each pair比较数据帧中的单词并计算每个对的最大单词长度的矩阵
【发布时间】:2019-11-14 02:01:50
【问题描述】:

我有一个包含许多唯一单词的数据框。我想在 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 中做到这一点?

【问题讨论】:

    标签: r dataframe matrix distance text-mining


    【解决方案1】:

    你也可以使用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
    

    【讨论】:

    • @zero,我要补充一点,sapply 解决方案无法很好地扩展,因为test 变得更长。但是,您可以轻松地将行名和列名添加到其他答案中。例如,对于outer 解决方案,您可以通过执行以下操作来设置列名和行名:colnames(mat) &lt;- rownames(mat) &lt;- test。假设您想要一个可以很好扩展的答案-我会接受outer 答案:)
    【解决方案2】:

    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
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      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)
      

      【讨论】:

        猜你喜欢
        • 2021-08-27
        • 1970-01-01
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多