计算两个对象的平均值 [英] Calculate mean value of two objects
问题描述
假设我们在开始时有两个对象:
Let's say we have two objects at the beginning:
a <- c(2,4,6)
b <- 8
如果我们在每个函数中应用mean()函数,则会得到以下结果:
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.
如果我创建一个合并a和b的新对象...
If I create a new object merging a and b...
c <- c(2,4,6,8)
并计算其平均值...
and calculate its mean...
> mean(c)
[1] 5
...我们得到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
我们可以看到,它的值与预期的正确值(5)不同.我想念什么?
As we can see, its value differs from the expected correct value (5). What am I missing?
推荐答案
如上所述,正确的解决方案是在将向量传递给mean
之前对其进行串联:
As mentioned, the correct solution is to concatenate the vectors before passing them to mean
:
mean(c(a, b))
您的原始代码给出错误结果的原因是由于mean
的第二个参数是:
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, ...)
因此,当使用两个数字参数调用mean
时,第二个参数将作为trim
参数传递,从而控制
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).
这篇关于计算两个对象的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!