Home > front end >  How to find the repartition of pairs in a 2-colum matrix in R?
How to find the repartition of pairs in a 2-colum matrix in R?

Time:12-14

Suppose I have a set of pairs that I represent it in a 2-columns matrix like this:

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

As you can see, the pair (2,6) has been repeated twice. I need to have a solution to retrieve information like this:

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

Is there any solution for this?

CodePudding user response:

An R base alternative:

> 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

CodePudding user response:

One method is count from dplyr after converting to data.frame

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

-output

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

data

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

CodePudding user response:

With the aggregate function:

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