R中矩阵中因子列的比例

R中矩阵中因子列的比例,r,sapply,R,Sapply,我想计算R中矩阵中因子水平的比例 样本数据: mtx <- matrix(NA, nrow=8, ncol=4) set.seed(12) wordclass <- c("Function", "Content", "Insert") for(i in 1:nrow(mtx)){ mtx[i,] <- sample(wordclass, 4, replace = T) } mtx [,1] [,2] [,3] [,4]

我想计算R中矩阵中因子水平的比例

样本数据:

mtx <- matrix(NA, nrow=8, ncol=4)
set.seed(12)
wordclass <- c("Function", "Content", "Insert")
for(i in 1:nrow(mtx)){
  mtx[i,] <- sample(wordclass, 4, replace = T)
}
mtx
     [,1]       [,2]       [,3]       [,4]      
[1,] "Content"  "Content"  "Insert"   "Insert"  
[2,] "Content"  "Function" "Function" "Content" 
[3,] "Insert"   "Content"  "Function" "Content" 
[4,] "Function" "Content"  "Content"  "Content" 
[5,] "Insert"   "Function" "Function" "Insert"  
[6,] "Content"  "Insert"   "Content"  "Function"
[7,] "Insert"   "Content"  "Function" "Function"
[8,] "Function" "Content"  "Insert"   "Content"

但是有没有一种方法可以通过数据帧转换在不绕道的情况下获得比例呢?

您可以使用
apply
,它对使用
MARGIN=2
的列的矩阵更有效

apply(mtx, 2, function(x) prop.table(table(factor(x, levels = wordclass))))

#          [,1]  [,2] [,3] [,4]
#Content  0.375 0.625 0.25 0.50
#Function 0.250 0.250 0.50 0.25
#Insert   0.375 0.125 0.25 0.25

您可以使用
apply
,它对列使用
MARGIN=2
的矩阵效果更好

apply(mtx, 2, function(x) prop.table(table(factor(x, levels = wordclass))))

#          [,1]  [,2] [,3] [,4]
#Content  0.375 0.625 0.25 0.50
#Function 0.250 0.250 0.50 0.25
#Insert   0.375 0.125 0.25 0.25

如果我们在数据集的
col
上执行
table
,我们可以以矢量化的方式执行此操作

prop.table(table(c(mtx), c(col(mtx))), 2)
#           1     2     3     4
#  Content  0.375 0.625 0.250 0.500
#  Function 0.250 0.250 0.500 0.250
#  Insert   0.375 0.125 0.250 0.250

如果我们在数据集的
col
上执行
table
,我们可以以矢量化的方式执行此操作

prop.table(table(c(mtx), c(col(mtx))), 2)
#           1     2     3     4
#  Content  0.375 0.625 0.250 0.500
#  Function 0.250 0.250 0.500 0.250
#  Insert   0.375 0.125 0.250 0.250

好奇:我以前似乎也尝试过同样的方法,但没有效果。现在是了。无论如何谢谢你!我想你需要先考虑一下?对于其中一个单词丢失的情况,好吧,当我尝试应用时,我没有考虑,这可能就是它不起作用的原因。谢谢@StupidWolf好奇:我以前似乎也尝试过同样的方法,但没有成功。现在是了。无论如何谢谢你!我想你需要先考虑一下?对于其中一个单词丢失的情况,好吧,当我尝试应用时,我没有考虑,这可能就是它不起作用的原因。谢谢@StupidWolf