计算平均值和其他排除某些值的值 [英] Calculate mean and other excluding certain values
问题描述
我有一个日期框架("daten"),其中大多数列都是数字值.它们通常介于0到5之间.但是,它们也可以取值99.我想计算列的均值,仅排除值99.
I have a date frame ("daten"), in which most columns are of numeric value. They typically range from 0 to 5. However, they can also take on the value 99. I want to calculate the mean of the columns, excluding only the values 99.
例如:
> mean(c(0, 1, 2, 3, 4, 5, 99))
[1] 16.28571
不是我所需要的,相反,我希望像向量一样对它进行计算
is not what I need, instead I want it to be calculated as if the vector was
> mean(c(0, 1, 2, 3, 4, 5))
[1] 2.5
,给了我我要搜索的意思.
, giving me the mean I am searching for.
出现了类似的问题(通过排除任何给定的数字),但该解决方案对我不起作用.但是,我发现一旦可以在任何列中排除某个值,就可以将其与apply
进行简单组合,因此我实际上正在寻找一种方法来计算某个矢量的均值,而忽略了某些值. /p>
There has been a similar question (Calculate mean, median by excluding any given number), but the solution does not work for me. I figured, however, that once I can exclude a certain value in any column, I can simply combine it with apply
, so I am actually looking for a way to calculate a mean for a certain vector, but ignoring certain values.
推荐答案
我们可以用NA replace
值'99'并用na.rm = TRUE
We can replace
the value '99' with NA and get the mean
with na.rm = TRUE
mean(replace(v1, v1==99, NA), na.rm = TRUE)
#[1] 2.5
数据
v1 <- c(0, 1, 2, 3, 4, 5, 99)
这篇关于计算平均值和其他排除某些值的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!