Calculate mean value of two objects

我是研究僧i 提交于 2019-12-04 05:51:42

问题


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?


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/48810286/calculate-mean-value-of-two-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!