在嵌套列表中应用函数 [英] Applying a function across nested list
本文介绍了在嵌套列表中应用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说,我有以下列表
raw <- list(list(1:2, 2:3, 3:4), list(4:5, 5:6, 6:7), list(7:8, 8:9, 9:10))
我想找到最外层列表中相应条目的均值.预期的输出将类似于
I would like to find the mean of the corresponding entries of the out-most list. The expected output would be something like
[[1]]
[1] 4 5
[[2]]
[1] 5 6
[[3]]
[1] 6 7
这是因为1:2
,4:5
和7:8
的平均值将是4:5
.
This is because the mean of 1:2
, 4:5
, and 7:8
would be 4:5
.
我一直在尝试lapply(raw, function(x) lapply(x, mean))
之类的东西,但是显然它没有返回期望的输出.
I have been experimenting with stuff like lapply(raw, function(x) lapply(x, mean))
, but apparently it doesn't return the desired output.
推荐答案
1
n = length(raw[[1]])
lapply(1:n, function(i){
d = do.call(rbind, lapply(seq_along(raw), function(j){
raw[[j]][[i]]
}))
apply(d, 2, mean)
})
#[[1]]
#[1] 4 5
#[[2]]
#[1] 5 6
#[[3]]
#[1] 6 7
2
aggregate(. ~ ind, do.call(rbind, lapply(raw, function(x)
data.frame(cbind(do.call(rbind, x), ind = seq_along(x))))), mean)
# ind V1 V2
#1 1 4 5
#2 2 5 6
#3 3 6 7
这篇关于在嵌套列表中应用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文