-2

I am looking for an easy way to count the number of unique combinations in a big binary matrix.

If I have the following matrix:

m = matrix(c(1,0,1,1,1,1,1,0,1,1,0,1), ncol=3, byrow=TRUE)

I would like to get the following output:

     [,1] [,2] [,3] [,4]
[1,]    1    0    1    3
[2,]    1    1    1    1

So the function should count the number of unique combinations of columns - there are three rows that contains 1,0,1, and one row that contains 1,1,1.

The object type is not fixed (i.e. it can be a data.frame, data.table, whatever). I would like to avoid having to specify the columns, to count over, by hand, if possible (i.e. i can supply a character vector with the corresponding column names, or use the whole matrix).

I know there has to be a solution, but my google fu seems to weak.

Cath
  • 23,906
  • 5
  • 52
  • 86
user680111
  • 971
  • 1
  • 9
  • 17

1 Answers1

3

One way is to use count from plyr:

library(plyr)
count(m, 1:ncol(m))

#  x.1 x.2 x.3 freq
#1   1   0   1    3
#2   1   1   1    1
989
  • 12,579
  • 5
  • 31
  • 53
  • 1
    Thank you so much - I've tried doing just that, and in the end i had a name collision in the workspace. It works perfectly – user680111 Oct 04 '16 at 09:02