Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用mapply计算多个列表的平均值_R_Mean_Lapply_Mapply - Fatal编程技术网

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

R 使用mapply计算多个列表的平均值,r,mean,lapply,mapply,R,Mean,Lapply,Mapply,数据集 firstList <- list(a = 1:3, b = 4:6) secondList <- list(c = 7:9, d = 10:12) 它不起作用,因为mean仅根据 这是正确的: mapply(mean, firstList) mapply(mean, secondList) 然后,我尝试lappy一次提供一个列表给mappy lapply(c(firstList, secondList), function(x) mapply(mean, x))

数据集

firstList  <- list(a = 1:3, b = 4:6)
secondList <- list(c = 7:9, d = 10:12)
它不起作用,因为
mean
仅根据

这是正确的:

mapply(mean, firstList)
mapply(mean, secondList)
然后,我尝试
lappy
一次提供一个列表给
mappy

lapply(c(firstList, secondList), function(x) mapply(mean, x))
输出不是平均值,而是单个列表

我需要的是如何使用
mapply
计算多个列表的
平均值。我还希望解释一下为什么
mapply
没有返回“平均值”列表


事先非常感谢

根据
的意思
,用法是

mean(x, ...)
mapply
中,我们有'x'和'y',因此我们可以将相应的
列表
元素串联成单个'x',然后取
平均值

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

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

如果我们使用的是
apply
函数的组合,我们可以使用
Map
连接,然后使用
sapply
循环
列表
元素,以获得
平均值

mapply(function(x,y) mean(c(x,y)), firstList, secondList)
#a b 
#5 8 
sapply(Map(c, firstList, secondList), mean)
# a b 
#5 8 
或者,如果
列表
元素的
长度
相同,我们可以使用
colMeans
,因为
mapply/c
输出是一个
矩阵
,没有
SIMPLIFY=FALSE

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

非常感谢,您是说函数的参数数必须等于要平均的列表数,对吗?@ragysaac它与
mean
中的参数有关,它只能取
x
,其中与
mappy/Map
一样,您有x,y,。。。取决于列表的数量。此外,如果有许多列表,而不是指定
函数(x,y,z,u)
,您可以使用
c
连接所有相应的列表元素,然后使用
sapply
获得
平均值,或者如果长度相同,则使用
colMeans
。@ragysaac另一个选项是
库(data.table);rbindlist(list(firstList,secondList))[,lapply(.SD,mean)]
@ragysaac如果您查看
c(firstList,secondList)
的输出,它是一个长度为4的列表
lappy
将循环遍历列表元素。每个列表元素都是一个向量。在该向量上应用
mapply
,就像再次循环每个向量元素,而执行
mean
只是执行单个值的
mean
。@ragysaac如果要在串联后获得每个列表元素的平均值,
lappy(c(firstList,secondList),function(x)mappy(mean,list(x)))
或只是
lappy(c(第一个列表,第二个列表),平均值)