Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element wise mean of multiple lists in R

Tags:

list

r

mean

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.

like image 606
hora Avatar asked Dec 25 '22 23:12

hora


2 Answers

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.

like image 74
Jilber Urbina Avatar answered Jan 05 '23 05:01

Jilber Urbina


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.

like image 39
Hong Ooi Avatar answered Jan 05 '23 05:01

Hong Ooi