# How to get column-wise frequencies in R? [closed]

Let's suppose I have the following matrix:

some_matrix <- matrix(c(2,2,2,1,3,1,3,1,3),nrow=3,ncol=3)


I am trying to get the frequencies of the values 1,2 and 3 per column. More precisely, I would like to get a data frame that shows the frequencies for all different values in column 1 and so on for the other columns. That is something like the following:

goal <- matrix(c(0,2,1,3,0,0,0,1,2),nrow=3,ncol=3)


I would appreciate some help! Thank you very much!

One way to do it is to use apply with the table function. Converting to a factor avoids having table leave out the values that don't appear in a particular column.

> goal
[,1] [,2] [,3]
[1,]    0    3    0
[2,]    2    0    1
[3,]    1    0    2

> t(apply(some_matrix, 2, function(x) table(factor(x, levels=1:3))))
1 2 3
[1,] 0 3 0
[2,] 2 0 1
[3,] 1 0 2

• this is gorgeous! Thank you so much for the fast reply! – Patrick Balada Mar 8 '16 at 10:04
• @PatrickBalada You're welcome. Thank you for including a reproducible example. – mark999 Mar 8 '16 at 10:04