[英]na.rm for other values in R
我有一個數據框
df=data.frame(a=1:5,b=c(1,3,4,-999999,4))
並想要計算平均值,但想排除異常值,在這種情況下為-9999
是否有類似的命令
na.rm
所以我可以去
apply(df,1,function(x) mean(if x>-100 & x <100))
請注意,我的df如果600 x 50暗淡
我們可以根據邏輯條件將'df'中的值replace
為NA並使用rowMeans
。
rowMeans(replace(df, !(df < 100 & df > -100) , NA), na.rm=TRUE)
#[1] 1.0 2.5 3.5 4.0 4.5
或如評論中提到的@RHertel
rowMeans(replace(df, abs(df) > 100 , NA), na.rm=TRUE)
#[1] 1.0 2.5 3.5 4.0 4.5
或另一種選擇是遍歷'df'的列,使用boxplot.stats
獲得離群值觀測值,將離群值轉換為NA
並執行rowMeans
。
rowMeans(sapply(df, function(x) x*NA^(x %in% boxplot.stats(x)$out)), na.rm=TRUE)
#[1] 1.0 2.5 3.5 4.0 4.5
如果您想要整個數據框架的均值,則可以采用以下方法:
mean(df[df > -100 & df < 100])
當我將其應用於您提供的df時,我會得到預期的答案:3。
您編寫自己的函數,但不包含-9999的值
y<-function(x){mean(x[!grepl("\\-999",x)])}
y(df$b)
[1] 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.