尝试在多个列表中生成平均值

时间:2015-01-18 20:05:25

标签: r list

我在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"))

每个列表显示给定数据集的0&1和1的数量。

> head(dta)
[[1]]

  0   1 
128 175 

[[2]]

  0   1 
132 171 

[[3]]

  0   1 
130 173 

[[4]]

  0   1 
133 170 

我习惯使用的lapply()函数在列表中运行(即查找给定列表中元素的总和)。在这里,我希望列表中的平均值。同样地,我想要在每个列表中出现0和1的平均数(即平均0&#39; s我想要128,132,130,133除以4的总和)。

任何建议都将不胜感激。

5 个答案:

答案 0 :(得分:5)

你可以尝试

library(reshape2)
library(data.table)
setDT(melt(dta))[, mean(value), Var1]

或者

colMeans(do.call(rbind, dta))

答案 1 :(得分:5)

您可以使用tapply()

u <- unlist(dta)
tapply(u, names(u), mean)
#      0      1 
# 130.75 172.25 

答案 2 :(得分:4)

此处使用Reduce

的方法
Reduce(`+`, dta)/length(dta)
#      0      1 
# 130.75 172.25 

答案 3 :(得分:3)

另一种方法:

sapply(split(unlist(dta), 0:1), mean)
#      0      1 
# 130.75 172.25 

答案 4 :(得分:3)

colMeans(matrix(unlist(dta), ncol = 2, byrow = TRUE))
#[1] 130.75 172.25

或与dplyr&amp; reshape2:

library(reshape2); library(dplyr)
melt(dta) %>% group_by(Var1) %>% summarise(mean = mean(value))
#Source: local data frame [2 x 2]
#
#  Var1   mean
#1    0 130.75
#2    1 172.25