数据库
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
没有返回列表的"平均值"
提前致谢
根据?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=FALSE
的matrix
colMeans(mapply(c, firstList, secondList))
#a b
#5 8