Element wise mean of multiple lists in R

三世轮回 提交于 2019-12-05 16:22:44

Assuming your As are lists of vectors:

Anames <- paste0("A", 1:10)

# for completeness
for(A in Anames)
    assign(A, lapply(1:7, function(x) rnorm(1000)))

sapply(1:7, function(i)
{
    m <- sapply(Anames, function(A) get(A)[[i]])
    mean(m)
})

This avoids building a copy of all your As in memory, instead retrieving them one at a time and extracting the desired vector. But if you have enough memory to store all that data, you could probably afford to store a copy as well.

If your A[[·]] are vectors as the following list,

> ( List <- list(A=1:4, B=5:8, C=9:12) )
$A
[1] 1 2 3 4

$B
[1] 5 6 7 8

$C
[1]  9 10 11 12

then you can use this approach to obtain the mean:

> rowMeans(simplify2array(List))
[1] 5 6 7 8

rowMeans(as.data.frame(List)) will give you the same result.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!