Let's say we have two objects at the beginning:
a <- c(2,4,6)
b <- 8
If we apply the mean() function in each of them we get this:
> mean(a)
[1] 4
> mean(b)
[1] 8
... which is absolutely normal.
If I create a new object merging a and b...
c <- c(2,4,6,8)
and calculate its mean...
> mean(c)
[1] 5
... we get 5, which is the expected value.
However, I would like to calculate the mean value of both objects at the same time. I tried this way:
> mean(a,b)
[1] 4
As we can see, its value differs from the expected correct value (5). What am I missing?
As mentioned, the correct solution is to concatenate the vectors before passing them to mean
:
mean(c(a, b))
The reason that your original code gives a wrong result is due to what mean
’s second argument is:
## Default S3 method:
mean(x, trim = 0, na.rm = FALSE, ...)
So when calling mean
with two numeric arguments, the second one is passed as the trim
argument, which, in turn, controls how much trimming is to be done. In your case, 8
causes the function to simply return the median (meaningful values for trim
would be fractions between 0 and 0.5).
If you print the argument a,b
that you are feeding into the mean
function, you will see that only a
prints:
print(a,b)
[1] 2 4 6
So mean(a,b)
only provides the mean of a
.
mean(c(a,b))
will produce the expected answer of 5.