There are two examples of function Reduce()
in Hadley Wickham's book Advanced R. Both work well.
Reduce(`+`, 1:3) # -> ((1 + 2) + 3)
Reduce(sum, 1:3) # -> sum(sum(1, 2), 3)
However, when using mean
in Reduce()
, it does not follow the same pattern. The outcome is always the first element of the list.
> Reduce(mean, 1:3)
[1] 1
> Reduce(mean, 4:2)
[1] 4
The two functions sum()
and mean()
are very similar. Why one works fine with Reduce()
, but the other does not? How do I know a if a function behaves normally in Reduce()
before it gives incorrect result?
This has to do with the fact that, unlike sum
or +
, mean
expects a single argument (re: a vector of values), and as such cannot be applied in the manner that Reduce
operates, namely:
Reduce uses a binary function to successively combine the elements of a given vector and a possibly given initial value.
Take note of the signature of mean
:
mean(x, ...)
When you pass multiple values to it, the function will match x
to the first value and ignore the rest. For example, when you call Reduce(mean, 1:3)
, this is more or less what is going on:
mean(1, 2)
#[1] 1
mean(mean(1, 2), 3)
#[1] 1
Compare this with the behavior of sum
, which accept a variable number of values:
sum(1, 2)
#[1] 3
sum(sum(1, 2), 3)
#[1] 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With