I have many lists contained within a larger list. I want to take the mean of the same entry in each of the lists.
Since I have many lists (100 plus) I want to be able to take the mean of all these lists by using 1:100 like I would for vector entries.
Here is some example, non working code.
## Make two lists
list_1 <- list()
list_1[[1]] <- 2
list_2 <- list()
list_2[[1]] <- 4
##Make a larger list to put the lists in
big_list <- list()
## Add lists to a larger list
big_list[[1]] <- list_1
big_list[[2]] <- list_2
## This doesn't work
mean(big_list[[1]][1], big_list[[2]][1], na.rm=TRUE)
## This does not work, but it is what I want
mean(big_list[[1:2]][1])
CodePudding user response:
You can use getElement
inside sapply
to pick out a vector comprising the first (or any specified) element from each sub-list:
sapply(big_list, getElement, 1)
#> [1] 2 4
and therefore
mean(sapply(big_list, getElement, 1))
#> [1] 3
CodePudding user response:
We could combine flatten
from purrr
package with unlist
:
library(purrr)
x <- unlist(flatten(big_list))
x
mean(x, na.rm = TRUE)
[1] 3
CodePudding user response:
This approach will do it as well:
sapply(1:length(big_list[[1]]), function(i) mean(sapply(big_list, function(x) x[[i]]), na.rm = TRUE))