Element wise mean of multiple lists in R

此生再无相见时 提交于 2019-12-07 11:03:11

问题


I have ten huge lists(each list has seven element but elements are huge) and I need to calculate the element wise mean of these lists. So if there are A1, A2, A3,..., A10 lists. I need to calculate :

mean1 = mean(A1[[1]], A2[[1]], A3[[1]], ...,A10[[1]])
.
.
.
mean7 = mean(A1[[7]], A2[[7]], A3[[7]], ....A10[[7]])

I have done it with for loop but I wanted to know if there is a better solution provided by R. Thank you in advance.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17815619/element-wise-mean-of-multiple-lists-in-r

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