I am trying to apply the table () function to a matrix in R. I want to know how often the value (0,1) appears on the column. There is no problem if the column contains both 1 and 0. But if the column contains only 1 or only 0, then apply () returns a strange list instead of a matrix.
How can I apply to return a matrix, as in example 1 for matrix 2?
good_mat<-matrix(c(c(1,0,1),c(1,0,1),c(0,0,1)), 3,3, byrow=F)
apply(good_mat, 2, FUN=table)
bad_mat<-matrix(c(rep(1,3),c(1,NA,1),c(0,0,1)), 3,3, byrow=F)
apply(bad_mat, 2, FUN=table)
edit: matrix may contain nAs
source
share