从R中的数据框中删除异常值?

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

我试图从我的数据中删除异常值。在我的情况下,异常值是在箱线图上绘制时远离其余数据的值。删除异常值后,我将数据保存在新文件中并运行一些预测模型以查看结果。它们与原始数据有多么不同。

我使用了一个tutorial并采用它来删除我的数据中的异常值。本教程使用boxplotting来计算异常值。

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

这是代码:

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
r outliers
1个回答
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,详细阐述了这一点。

© www.soinside.com 2019 - 2024. All rights reserved.