David Lee David Lee - 1 month ago 7
R Question

Mean(or other function) of corresponding elements of a list in R

I have a list, each element in this list is a vector and have same length. I want to calculate the mean(or other value, it can be a user-defined function) of all first element of each vector, mean(or other value, it can be a user-defined function) of all second element of each vector, etc. And return a vector. So this is different from question How to sum a numeric list elements in R .Following code gave me the exactly what I want, however, is there any more efficient and sophistical way to do this? Thanks.

list1 <- list(a=1:5,b=2:6,c=3:7)
result <- numeric(length(list1[[1]]))
for(i in 1:length(list1[[1]])){
result[i] <- mean(c(list1[[1]][i],list1[[2]][i],list1[[3]][i])) #the function can be any other function rather than mean()
}

Answer

Here's an option using the Reduce function:

Reduce("+",list1)/length(list1)
[1] 2 3 4 5 6
Comments