使用mapply计算多个列表的均值

Using mapply to calculate the mean of more than one list

数据集

firstList  <- list(a = 1:3, b = 4:6)
secondList <- list(c = 7:9, d = 10:12)

我正在尝试使用 mapply 计算多个列表的平均值。

mapply(mean, firstList, secondList)

它不起作用,因为 mean 仅根据

这可以正常工作:

mapply(mean, firstList)
mapply(mean, secondList)

然后我尝试 lapply 一次提供一个列表给 mapply

lapply(c(firstList, secondList), function(x) mapply(mean, x))

输出的不是平均值而是单个列表

我需要的是如何使用mapply计算多个列表的mean。我也很感激解释为什么 mapply 没有 return 列表`mean'

非常感谢

根据?mean,用法是

mean(x, ...)

mapply中,我们有'x'和'y',所以我们可以将相应的list元素连接起来,形成一个'x',然后采取 mean

mapply(function(x,y) mean(c(x,y)), firstList, secondList)
#a b 
#5 8 

相同
mean(c(1:3, 7:9))
#[1] 5

如果我们使用 apply 函数的组合,我们可以与 Map 连接,然后使用 sapply 循环 list 元素以获得 mean

sapply(Map(c, firstList, secondList), mean)
# a b 
#5 8 

或者如果 list 元素的 lengths 相同,我们可以使用 colMeans 因为 mapply/c 输出是 matrix 而没有 SIMPLIFY=FALSE

colMeans(mapply(c, firstList, secondList)) 
#a b 
#5 8