如何在多个列中用NA有条件地替换值 [英] How to conditionally replace values with NA across multiple columns

查看:54
本文介绍了如何在多个列中用NA有条件地替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用NA替换数据框每列中的离群值.

I would like to replace outliers in each column of a dataframe with NA.

例如,如果我们将离群值定义为离均值大于3个标准差的任何值,我可以使用以下代码实现此每个变量.

If for example we define outliers as being any value greater than 3 standard deviations from the mean I can achieve this per variable with the code below.

我希望在一个调用中对 df 的所有列执行相同的操作,而不是单独指定每个列.关于如何执行此操作的任何指示?

Rather than specify each column individually I'd like to perform the same operation on all columns of df in one call. Any pointers on how to do this?!

谢谢!

library(dplyr)
data("iris")
df <- iris %>% 
  select(Sepal.Length, Sepal.Width, Petal.Length)%>% 
  head(10) 

# add a clear outlier to each variable
df[1, 1:3] = 99

# replace values above 3 SD's with NA
df_cleaned <- df %>% 
  mutate(Sepal.Length = replace(Sepal.Length, Sepal.Length > (abs(3 * sd(df$Sepal.Length, na.rm = TRUE))), NA))

推荐答案

您需要使用 mutate_all(),即

library(dplyr)

df %>% 
 mutate_all(funs(replace(., . > (abs(3 * sd(., na.rm = TRUE))), NA)))

这篇关于如何在多个列中用NA有条件地替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆