Apply () and table () return a strange list when a column has only one value (100%)

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?

#example 1
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) # good result, matrix

#example 2
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) # strange list

edit: matrix may contain nAs

+4
source share
3 answers

I recommend the package matrixStats,

library(matrixStats)
 rbind(colCounts(good_mat, value = 0, na.rm = TRUE), 
       colCounts(good_mat, value = 1, na.rm = TRUE))

#     [,1] [,2] [,3]
#[1,]    0    1    3
#[2,]    3    2    0
+3
source

Basic solution:

m <- matrix(c(c(1,1,1),c(1,0,1),c(0,0,0)), 3,3, byrow=F)

rbind(nrow(m) - rowSums(m, na.rm = TRUE), rowSums(m, na.rm = TRUE))
     [,1] [,2] [,3]
[1,]    0    1    3
[2,]    3    2    0

or

tmp <- colSums(m, na.rm = TRUE)
rbind(nrow(m) - tmp, tmp)
+2
source

R- colSums rbind .

rbind((colSums(bad_mat == 0)), (colSums(bad_mat == 1)))
     [,1] [,2] [,3]
[1,]    0    1    2
[2,]    3    2    1

or, to summarize more than binary values, you can wrap this in lapplyand pass it to do.call. Just replace 0:1with the desired values.

do.call(rbind, lapply(0:1, function(i) colSums(bad_mat == i)))
     [,1] [,2] [,3]
[1,]    0    1    2
[2,]    3    2    1
+1
source

Source: https://habr.com/ru/post/1666612/


All Articles