tomka
tomka

Reputation: 2638

Sum of two lists

How can I generally take the sum of the elements of two lists that contain conformable matrices?

  l1<-list(matrix(1,3,3),matrix(2,3,3))
  l2<-list(matrix(3,3,3),matrix(4,3,3))

where the sum is defined as:

  l3<-list(l1[[1]]+l2[[1]],l1[[2]]+l2[[2]])

and 'generally' implies matrices of any size and lists of any length.

Upvotes: 2

Views: 5573

Answers (1)

shadow
shadow

Reputation: 22313

This is a typical case for the mapply function:

mapply("+", l1, l2, SIMPLIFY = FALSE)

Or slightly more concisely using Map, which is just mapply with different defaults.

Map("+", l1, l2)

Upvotes: 6

Related Questions