Frost_Maggot
Frost_Maggot

Reputation: 309

Why does mapply() behave differently depending on the function called?

I am hoping someone can help me understand why the mapply function behaves differently when you call the sum function and when you call the mean function.

My question is probably better explained by looking at this MWE (partly borrowed from https://nsaunders.wordpress.com/2010/08/20/a-brief-introduction-to-apply-in-r/)

l1 <- list(a = c(1:10), b = c(11:20))
l2 <- list(c = c(21:30), d = c(31:40))

mapply(sum, l1$a, l1$b, l2$c, l2$d)

[1]  64  68  72  76  80  84  88  92  96 100

The above code returns 10 values, the sum of the corresponding elements in each object a, b, c and d.

The following example does not work in the same manner:

mapply(mean, l1$a, l1$b, l2$c, l2$d)

[1]  1  2  3  4  5  6  7  8  9 10

In the latter example it seems like b, c and d are being ignored and it is just calculating the mean of each element of a.

If someone could help me understand this that would be great.

Many thanks!

Upvotes: 0

Views: 72

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70623

mapply works as expected. It sums or means element-wise from lists of elements. For example:

l1$a[1] + l1$b[1] + l2$c[1] + l2$d[1]

[1] 64

mean(l1$a[1], l1$b[1], l2$c[1], l2$d[1])

[1] 1

Note that mean only uses the first argument because it only accepts x (see ?mean).

> mean(l1$a[1])
[1] 1
> mean(l1$a[1], l1$b[1])
[1] 1

You may want to use rapply.

l <- list(l1, l2)
rapply(l, mean)

   a    b    c    d 
 5.5 15.5 25.5 35.5 

Upvotes: 3

Related Questions