I have several lists containing vectors and I would like to obtain a single list, which elements are the mean vectors of the vectors of the initial lists.
Example: Two initial lists
lt1 <- list(a = c(1,2,3), b = c(2,5,10))
lt2 <- list(a = c(3,4,5), b = c(4,5,2))
And I would like to obtain
lt12 <- list(a = c(2,3,4), b = c(3,5,6))
I tried with lapply and llply, but I always end up obtaining the mean of the vector of each list.
You could use Map()
to cbind()
the vectors together, then run rowMeans()
on the resulting list.
lapply(Map(cbind, lt1, lt2), rowMeans)
# $a
# [1] 2 3 4
#
# $b
# [1] 3 5 6
Or the other way with lapply(Map(rbind, lt1, lt2), colMeans)
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