在 apply 函数中用零值计数

Counting with zero values in the apply function

我正在尝试根据应用函数中定义的列表使用出现次数为零的计数。我已经设法分别完成这些,但理想情况下希望将它们放在一行中。这是我的目标:

list <- c("x", "y", "z")

df       
    V1   V2   V3
    x    y    y
    x    x    z
    y    z    z

想要的结果

     V1    V2   V3
 x   2     1    0
 y   1     1    1
 z   0     1    2

所以我设法为单个专栏执行此操作:

out <- table(factor(df$V1,levels=list))

对于没有定义列表的所有列(因此没有零出现)

occurences <- (apply(df,2,(table)))

所以理想情况下我想要一个在另一个里面,例如:

occurences <- as.data.frame(apply(df,2,(table(factor(df,levels=list)))))

可悲的是,R 对此感到不安并说 (table(factor(df,levels=list) 不是一个函数。任何帮助将不胜感激。

你就快完成了,正如错误所说,你只需要在apply:

中定义一个函数
apply(df, 2, function(u) table(factor(u, levels=vec)))
#  V1 V2 V3
#x  2  1  0
#y  1  1  1
#z  0  1  2

您还可以使用 lapply 函数迭代 data.frame:

的列
do.call(rbind,lapply(df, function(u) table(factor(u, levels=vec))))
#   x y z
#V1 2 1 0
#V2 1 1 1
#V3 0 1 2

请注意,将矢量命名为 "list" 确实具有误导性。 list 也是 R 语言的关键字,所以我将你的向量重命名为 "vec"。

数据:

vec = c("x", "y", "z")

df = structure(list(V1 = structure(c(1L, 1L, 2L), .Label = c("x", 
"y"), class = "factor"), V2 = structure(c(2L, 1L, 3L), .Label = c("x", 
"y", "z"), class = "factor"), V3 = structure(c(1L, 2L, 2L), .Label = c("y", 
"z"), class = "factor")), .Names = c("V1", "V2", "V3"), row.names = c(NA, 
-3L), class = "data.frame")

这是我的解决方案,使用胶合板 rbind.fill:

df <- read.table(header = TRUE, text = '   V1   V2   V3
x    y    y
x    x    z
y    z    z')

require(plyr)
out <- rbind.fill(lapply(df, function(x) as.data.frame.matrix(t(table(x)))))
out[is.na(out)] <- 0
out
#   x y z
# 1 2 1 0
# 2 1 1 1
# 3 0 1 2