为矩阵的每一列获取偶然性 table

Get contingency table for each column of a matrix

假设我有一个数字矩阵。矩阵有dim(X)=(200,5),每个元素都在1到5之间。

我想知道每列中每个数字的计数。看起来像

的东西
  X1 X2 X3 X4 X5
1 #  #  #  #  #
2 #  #  #  #  #
3 #  #  #  #  #
4 #  #  #  #  #
5 #  #  #  #  #

由于有 200 行,每列的总和应为 200。

table 看起来很有希望,但它只是 returns 整个矩阵的计数,而不是列的计数。我怎样才能做到这一点?

一般情况下我会这样做。例如

  • 当你有一个字母矩阵时;
  • 当你仍然有一个整数矩阵但它们不连续时,比如 5、7、10、11、20。

--

cX <- c(X)
k <- sort(unique(cX))
## as if we have a matrix of factors
XX <- matrix(match(cX, k), dim(X)[1], dimnames = list(k, 1:dim(X)[2]))
## aligned column-wise contingency table
tab <- apply(XX, 2, tabulate)
## aligned column-wise proportion table
prop <- tab / colSums(tab)[col(tab)]

我放弃了我最初的回答

lapply(data.frame(X), table)
apply(X, 2, table)

或第二个版本(更健壮,但与第一个解决方案一样低效):

k <- sort(unique(c(X)))
apply(X, 2, function (u) table(factor(u, levels = k)) )

上面的新答案有点 "overkill" 你的例子,但在实践中更有用(我认为)。

基数 R 中的 tabulate 怎么样:

apply(m,2,tabulate)

#    [,1] [,2] [,3] [,4] [,5]
#[1,]   39   47   38   42   34
#[2,]   41   43   41   36   39
#[3,]   46   33   38   44   39
#[4,]   35   31   40   41   53
#[5,]   39   46   43   37   35

table:

apply(m,2,table)

数据

set.seed(1)
m <- t(replicate(200,sample(5),))