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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With