How to calculate the average value of vectors from multiple lists?

I have several lists containing vectors, and I would like to get one list, which elements are the middle vectors of the vectors of the source lists.

Example: two start 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 receive

 lt12 <- list(a = c(2,3,4), b = c(3,5,6)) 

I tried with foot and lplply, but always get the average vector value of each list.

+5
source share
1 answer

You can use Map() to cbind() vectors together, then run rowMeans() in the resulting list.

 lapply(Map(cbind, lt1, lt2), rowMeans) # $a # [1] 2 3 4 # # $b # [1] 3 5 6 

Or another way with lapply(Map(rbind, lt1, lt2), colMeans)

+2
source

All Articles