I have a list
like this:
(mylist <- list(a = data.frame(x = c(1, 2), y = c(3, 4)),
b = data.frame(x = c(2, 3), y = c(4, NA)),
c = data.frame(x = c(3, 4), y = c(NA, NA))))
$a
x y
1 1 3
2 2 4
$b
x y
1 2 4
2 3 NA
$c
x y
1 3 NA
2 4 NA
which is created by purrr::map()
. How can I calculate the means of values in the corresponding cells? i.e.
x y
1 2 3.5
2 3 4
where
mean(c(1, 2, 3), na.rm = T) # = 2
mean(c(2, 3, 4), na.rm = T) # = 3
mean(c(3, 4, NA), na.rm = T) # = 3.5
mean(c(4, NA, NA), na.rm = T) # = 4
Thanks for your help!
OR
A
purrr
optionOne method would be to convert your list to an array, and then to apply the mean function across the third dimension of the array:
If you wanted to do this all in one shot, without hard-coding the dimensions, you could do: