我在for()循环中填充列表.结果的样本包括在下面.
dta <- list(structure(c(128L, 175L), .Dim = 2L, .Dimnames = structure(list(
c("0", "1")), .Names = ""), class = "table"), structure(c(132L,
171L), .Dim = 2L, .Dimnames = structure(list(c("0", "1")), .Names = ""), class = "table"),
structure(c(130L, 173L), .Dim = 2L, .Dimnames = structure(list(
c("0", "1")), .Names = ""), class = "table"), structure(c(133L,
170L), .Dim = 2L, .Dimnames = structure(list(c("0", "1")), .Names = ""), class = "table"))
Run Code Online (Sandbox Code Playgroud)
每个列表显示给定数据集的0和1的数量.
> head(dta)
[[1]]
0 1
128 175
[[2]]
0 1
132 171
[[3]]
0 1
130 173
[[4]]
0 1
133 170
Run Code Online (Sandbox Code Playgroud)
lapply()我习惯使用的函数在列表中运行(即查找给定列表中元素的总和).在这里,我希望列表中的平均值.等效地,我想要在每个列表中出现0和1的平均数(即平均0,我想要128,132,130,133除以4的总和).
任何建议,将不胜感激.
你可以试试
library(reshape2)
library(data.table)
setDT(melt(dta))[, mean(value), Var1]
Run Code Online (Sandbox Code Playgroud)
要么
colMeans(do.call(rbind, dta))
Run Code Online (Sandbox Code Playgroud)
您可以使用 tapply()
u <- unlist(dta)
tapply(u, names(u), mean)
# 0 1
# 130.75 172.25
Run Code Online (Sandbox Code Playgroud)