如何使用IQR方法删除/消除异常值

时间:2014-11-25 13:54:34

标签: r statistics

我是R和R包的初学者。 我想问你下面的问题是否有任何明确的解决办法。我已经以.csv格式导入了我的数据,如下图所示

https://dl.dropboxusercontent.com/u/23801982/1234.jpg

这些是按实体年份分组的数据,大约是4个参数,您可以在下一列中看到。如果还产生例如Absrtactions列如下:

https://dl.dropboxusercontent.com/u/23801982/1234566.jpg

现在我正在尝试使用boxplot.stats命令识别异常值。

但我不知道如何排除从结果中排除异常值并将其导出到新文件(例如.txt或.csv)中,因为分组数据。我还看到了使用IQR计算的手动外部方法,但我认为它不适合所需的可导出数据集。

到目前为止我使用的代码是:

rm(list = ls())
library("gdata")

s1 <- read.csv("C:\\Users\\G\\Documents\\R\\Projects\\20141125.csv", header = T)

boxplot(s1$Abstractions ~ s1$Entity, col="green", srt=45) 

boxplot.stats(s1$Abstractions)

谢谢

1 个答案:

答案 0 :(得分:6)

您正在查看正确的函数boxplot.stats

查看R中可以使用的功能

?functionName

所以试试

?boxplot.stats

您将看到它在插槽调用中返回异常值

Value:

     List with named components as follows:

   stats: a vector of length 5, containing the extreme of the lower
          whisker, the lower ‘hinge’, the median, the upper ‘hinge’ and
          the extreme of the upper whisker.

       n: the number of non-‘NA’ observations in the sample.

    conf: the lower and upper extremes of the ‘notch’ (‘if(do.conf)’).
          See the details.

     out: the values of any data points which lie beyond the extremes
          of the whiskers (‘if(do.out)’).
     Note that ‘$stats’ and ‘$conf’ are sorted in _in_creasing order,
     unlike S, and that ‘$n’ and ‘$out’ include any ‘+- Inf’ values.

所以要删除异常值,你可以做这样的事情

outliersValue<- boxplot.stats(x)$out
x[!x %in% outliersValue]

其中x是您的数据。

%in%运算符将检查另一个值中是否存在值。添加!是一个否定运算符,在这种情况下,将反转逻辑,返回True x outliersValue中找不到的{{1}}

我希望你觉得这很有用。快乐的R-ing

相关问题