r语言 - 使用mapply计算多个列表的平均值



数据库

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

我试图用mapply计算多个列表的平均值。

mapply(mean, firstList, secondList)

它不能工作,因为mean只平均它的第一个参数在矩阵

上使用mapply和均值函数

可以正常运行:

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

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

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

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

我需要的是如何使用mapply计算多个列表的mean。我也希望解释为什么mapply没有返回列表的"平均值"

提前致谢

根据?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连接,然后将list元素与sapply循环以获得mean

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

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

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

最新更新