Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the mean of vectors from multiple lists?

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.

like image 845
user34771 Avatar asked Oct 30 '22 19:10

user34771


1 Answers

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)

like image 199
Rich Scriven Avatar answered Nov 14 '22 05:11

Rich Scriven