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.
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.
Assuming your A
s 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 A
s 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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With