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

XCe*_*ble 1 r outliers

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

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

当我在有异常值的列上运行它时,它工作得很好。但当我对没有异常值的列运行它时,它会引发错误。如何消除这个错误?

这是代码:

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)
Run Code Online (Sandbox Code Playgroud)

产生错误:

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)
Run Code Online (Sandbox Code Playgroud)

Mau*_*ers 6

以下作品

# 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), ]
Run Code Online (Sandbox Code Playgroud)

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

outliers <- boxplot(mtcars$mpg, plot = FALSE)$out
outliers
#numeric(0)
Run Code Online (Sandbox Code Playgroud)

比较

which(mtcars$mpg %in% outliers)
#integer(0)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

这里有一篇关于 SO 的很好的文章详细阐述了这一点。