0

I have a question regarding mapply which allows us to execute a function simultaneously over multiple lists specified as arguments.

See code below. Here mapply performs (l1$a[1] + l1$b[1] + l2$a[1] + l2$b[1]) up until (l1$a[10] + l1$b[10] + l2$c[10] + l2$d[10]). What if what I meant was for the sum function to work independently on each of the individual lists being l1$a, l1$b, l2$a, l2$b and return the sum of elements in each of those lists, so the output would be just four sums?

> l1 <- list(a = c(1:10), b = c(11:20))
> l2 <- list(a = c(21:30), b = c(31:40))
> mapply(sum, l1$a, l1$b, l2$a, l2$b)
 [1]  64  68  72  76  80  84  88  92  96 100
IAMTubby
  • 1,627
  • 4
  • 28
  • 40
  • 2
    I guess you need `sapply(append(l1, l2),sum)# a b a b 55 155 255 355` ` – akrun Dec 15 '14 at 16:03
  • 2
    Indeed, you can also use the c function you were asking some minutes ago. sapply(c(l1,l2),function(x) sum(x)) or sapply(c(l1,l2),sum) – zipp Dec 15 '14 at 16:12
  • You could also check http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega for – akrun Dec 15 '14 at 16:15

0 Answers0