【问题标题】:How to find the repartition of pairs in a 2-colum matrix in R?如何在 R 中的 2 列矩阵中找到对的划分?
【发布时间】:2022-01-17 02:54:25
【问题描述】:

假设我有一组对,我用这样的 2 列矩阵表示它:

> myMatrix
     [,1] [,2]
[1,]    1    5
[2,]    2    6
[3,]    3    7
[4,]    2    6

如您所见,这对 (2,6) 重复了两次。我需要一个解决方案来检索这样的信息:

     [,1] [,2] [,3]
[1,]    1    5   1
[2,]    2    6   2
[3,]    3    7   1

有什么解决办法吗?

【问题讨论】:

    标签: r dataframe counting


    【解决方案1】:

    R 基础替代方案:

    > x <- data.frame(table(myMatrix[, 1], myMatrix[, 2]))
    > subset(x, Freq!=0)
      Var1 Var2 Freq
    1    1    5    1
    5    2    6    2
    9    3    7    1
    

    【讨论】:

      【解决方案2】:

      一种方法是countdplyr转换为data.frame

      library(dplyr)
      as.data.frame(myMatrix) %>%
          count(across(everything())) %>%
          as.matrix %>%
          `dimnames<-`(., NULL)
      

      -输出

           [,1] [,2] [,3]
      [1,]    1    5    1
      [2,]    2    6    2
      [3,]    3    7    1
      

      数据

      myMatrix <- structure(c(1, 2, 3, 2, 5, 6, 7, 6), .Dim = c(4L, 2L))
      

      【讨论】:

        【解决方案3】:

        使用aggregate 函数:

        aggregate(m[,1], as.data.frame(m), length)
        #>   V1 V2 x
        #> 1  1  5 1
        #> 2  2  6 2
        #> 3  3  7 1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-09
          • 2020-02-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多