如何根据一列中所有其他数字的平均值重置一些离群值?

问题描述 投票:0回答:1

我需要用平均值替换大于平均值的2倍或小于列中所有其他数字的平均值的1/2的异常值。

例如,我有一个包含两列的数据集DT:

  • 日期= {1-1-2019,1-2-2019,1-3-2019,1-4-2019,1-5-2019,1-6-2019}
  • 价格= {2,3,2.5,2.7,28,20}

我需要用Price列中所有其他值的平均值替换异常值(此处为28和20)。因此,基本上我需要执行以下操作:

DT$Price[DT$Price>2*mean(2,3,2.5,2.7)|DT$Price<0.5*mean(2,3,2.5,2.7)] <- mean(2,3,2.5,2.7).

有人可以请我提供如何处理此问题的建议吗?谢谢!

r dplyr outliers
1个回答
0
投票

我想您需要的是

mean_p <- mean(df$Price)
inds <- df$Price > (2 * mean_p) | df$Price < (mean_p * 0.5)
df$Price[inds] <- mean(df$Price[!inds])

但是,在示例中,共享的mean_p9.7,并且数据帧中的所有Prices都大于19.42* 9.7)或小于4.850.5 * 9.7)。

数据

df <- data.frame(Date = c("1-1-2019","1-2-2019","1-3-2019","1-4-2019",
                          "1-5-2019","1-6-2019"), 
                 Price = c(2,3,2.5,2.7,28,20))
© www.soinside.com 2019 - 2024. All rights reserved.