user34771
user34771

Reputation: 455

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.

Upvotes: 5

Views: 1664

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

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)

Upvotes: 2

Related Questions