【问题标题】:Remove outliers from data frame in R?从R中的数据框中删除异常值?
【发布时间】:2019-02-20 09:08:15
【问题描述】:

我正在尝试从我的数据中删除异常值。在我的例子中,异常值是在箱线图上绘制时远离其余数据的值。去除异常值后,我会将数据保存在新文件中并运行一些预测模型来查看结果。它们与原始数据有何不同。

我使用了一个tutorial 并采用它来从我的数据中删除异常值。本教程使用箱线图来找出异常值。

当我在具有异常值的列上运行它时,它工作正常。但是当我为没有异常值的列运行它时会引发错误。如何消除此错误?

代码如下:

outlier_rem <- Data_combined #data-frame with 25 var, few have outliers

#removing outliers from the column

outliers <- boxplot(outlier_rem$var1, plot=FALSE)$out
#print(outliers)
ol <- outlier_rem[-which(outlier_rem$var1 %in% outliers),]

dim(ol)
# [1]  0 25
boxplot(ol)

产生错误:

no non-missing arguments to min; returning Infno non-missing arguments to max; 
returning -InfError in plot.window(xlim = xlim, ylim = ylim, log = log, yaxs = pars$yaxs) : 
  need finite 'ylim' values

【问题讨论】:

  • 你能举个数据例子吗?尝试代码:) 玩具数据也很完美! :)
  • 好的,我正在使用我提供的链接教程中的数据对其进行测试。我的数据太大了。请尝试 mtcars$disp[which(mtcars$disp >420)] 420)]*2) 用于异常值和 mtcars$disp[which(mtcars$disp >420 )] 用于错误的无异常值数据

标签: r outliers


【解决方案1】:

以下作品

# Sample data based on mtcars and one additional row
df <- rbind(mtcars[, 1:3], c(100, 6, 300))

# Identify outliers        
outliers <- boxplot(df$mpg, plot = FALSE)$out
#[1]  33.9 100.0

# Remove outliers
df[!(df$mpg %in% outliers), ]

你的方法失败的原因是因为如果没有outlierswhich(mtcars$mpg %in% numeric(0)) 返回integer(0),你最终得到一个零行data.frame,这正是你从dim 看到的。

outliers <- boxplot(mtcars$mpg, plot = FALSE)$out
outliers
#numeric(0)

比较

which(mtcars$mpg %in% outliers)
#integer(0)

df$mpg %in% outliers
# [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
#[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
#[25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

这里有一个nice post,详细说明了这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2017-10-26
    • 2018-03-23
    • 2017-04-24
    • 2021-03-24
    • 2018-01-09
    • 1970-01-01
    相关资源
    最近更新 更多