apply() 和 table() return 当列只有一个值时的奇怪列表 (100%)

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

我正在尝试将 table() 函数应用于 R 中的矩阵。我想知道每列出现值 (0,1) 的频率。 如果一列同时包含 1 和 0 则没有问题。但如果一列仅包含 1 或仅包含 0,则 apply() return 是一个奇怪的列表而不是矩阵。

如何将示例 1 中的矩阵 2 应用于 return 矩阵?

#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

编辑: 矩阵可以包含 NA

我推荐套餐 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

基本解决方案:

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

或者

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

这是一个基础 R 解决方案,colSums 用于计算值,rbind 用于组合结果。

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

或者,要概括超过二进制值,您可以将其包装在 lapply 中并将其提供给 do.call。只需将 0:1 替换为所需的值即可。

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