Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find frequency of each unique column in a matrix or data frame

Tags:

r

I want to find frequency of a matrix by their column. for example for matrix x below

   x <- matrix(c(rep(1:4,3),rep(2:5,2)),4,5)
   x
         [,1] [,2] [,3] [,4] [,5]
   [1,]    1    1    1    2    2
   [2,]    2    2    2    3    3
   [3,]    3    3    3    4    4
   [4,]    4    4    4    5    5

now how can find frequency of each unique column and create a matrix that each column is a unique column of x and the last row is added as the frequency of it in matrix x

 #freqmatrix
        [,1] [,2]
 [,1]      1  2
 [,2]      2  3
 [,3]      3  4
 [,4]      4  5
 [,5]      3  2
like image 580
morteza Avatar asked Dec 16 '22 15:12

morteza


1 Answers

Here is a solution avoiding converting the matrix to a list of lists, but it is also a little messy:

x.unique <- unique(x, MARGIN  = 2)

freq <- apply(x.unique, MARGIN = 2, 
              function(b) sum(apply(x, MARGIN = 2, function(a) all(a == b)))
        )

rbind(x.unique, freq)

     [,1] [,2]
        1    2
        2    3
        3    4
        4    5
freq    3    2
like image 162
orizon Avatar answered May 04 '23 00:05

orizon