从r中的多列中删除异常值
我使用以下代码来识别不同列上的异常值:
outliers_x1 <- boxplot(mydata$x1, plot=FALSE)$out
outliers_x4 <- boxplot(mydata$x4, plot=FALSE)$out
outliers_x6 <- boxplot(mydata$x6, plot=FALSE)$out
现在,如何通过一个代码从数据集中删除这些异常值?
I used below codes to identify outliers on different columns:
outliers_x1 <- boxplot(mydata$x1, plot=FALSE)$out
outliers_x4 <- boxplot(mydata$x4, plot=FALSE)$out
outliers_x6 <- boxplot(mydata$x6, plot=FALSE)$out
Now, how can I remove those outliers from the dataset by one code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将把任何离群值设置为
na
,然后选择删除所有列包含异常值的所有行。使用任意数量的列。为方便起见,使用
data.table
。在上面,
indx
是具有三个逻辑列的矩阵。每个元素都是true
,除非相应的列在该行中包含一个异常值。我们使用rowprods(...)
从matrixstats
package toply(&amp;
)一起使用3行。不幸的是,这将转换所有数字(1,0),因此我们必须将用作索引的逻辑转换回逻辑> dt 。在上面的代码中,我们添加了
id
列,然后熔体(...)
,因此所有其他列都在一个列中(value
),第二列(<代码>变量),指示原始源列。然后,我们将boxplot(...)
算法group-wise(通过variable
)生成ol
列指示异常值。然后,我们将任何value
设置为ol == true
对应于na
。然后,我们使用dcast(...)
将您的原始宽格式重新转换为您的原始宽格式,然后删除id
。这有点回旋,但是在处理这样的多列时,这种熔体 - 过程 - 播放模式很常见。
最后,
na.omit(结果)
将删除任何列中具有na
的行。如果那是您想要的,则使用第一种方法会更简单。This will set any outlier values to
NA
, and then optionally remove all rows where any column contains an outlier. Works with arbitrary number of columns.Uses
data.table
for convenience.In the above,
indx
is a matrix with three logical columns. Each element isTRUE
unless the corresponding column contained an outlier in that row. We userowProds(...)
from thematrixStats
package to multiply (&
) the 3 rows together. Unfortunately this converts everything numeric (1, 0), so we have to convert back to logical to use as an index intodt
.In the code above we add an
id
column, thenmelt(...)
so all other columns are in one column (value
) with a second column (variable
) indicating the original source column. Then we apply theboxplot(...)
algorithm group-wise (byvariable
) to produce anol
column indicating an outlier. Then we set anyvalue
corresponding tool == TRUE
toNA
. Then we re-convert to your original wide format withdcast(...)
and remove theid
.It's a bit roundabout but this melt - process - dcast pattern is common when processing multiple columns like this.
Finally,
na.omit(result)
will remove any rows which haveNA
in any of the columns. If that's what you want it's simpler to use the first approach.