使用标称变量删除 r 中的异常值

deleting outlier in r with account of nominal var

说,我有三列

x <- c(-10, 1:6, 50)
x1<- c(-20, 1:6, 60)
z<- c(1,2,3,4,5,6,7,8)

检查 x 的异常值

bx <- boxplot(x)
bx$out

检查 x1 的异常值

bx1 <- boxplot(x1)
bx1$out

现在我们必须删除异常值

x <- x[!(x %in% bx$out)]
x

x1 <- x1[!(x1 %in% bx1$out)]
x1

但是我们有变量 Z(标称),我们必须删除对应于变量 x 和 x1 的离群值的观测值, 在我们的例子中是 1 和 8 obs。 Z

怎么做? 在输出中我们必须有

x   x1  z
Na  Na  Na
1   1   2
2   2   3
3   3   4
4   4   5
5   5   6
6   6   7
Na  Na  Na

试试这个解决方案:

x_to_remove<-which(x %in% bx$out)
x <- x[!(x %in% bx$out)]

x1_to_remove<-which(x1 %in% bx1$out)
x1 <- x1[!(x1 %in% bx1$out)]

z<-z[-unique(c(x_to_remove,x1_to_remove))]
z    
[1] 2 3 4 5 6 7

在删除 xx1 中的值之前,您必须保存位置(x_to_removex1_to_remove),然后用于清理 z

你的输出:

data.frame(cbind(x,x1,z))
  x x1 z
1 1  1 2
2 2  2 3
3 3  3 4
4 4  4 5
5 5  5 6
6 6  6 7

如果你有一个数据框

x  <- c(-10, 1:6, 50)
x1 <- c(-20, 1:6, 60)
z  <- c(1,2,3,4,5,6,7,8)
df <- data.frame(x = x, x1 = x1, z = z)

您可以执行此操作以删除 xx1

中具有异常值的行
is.outlier <- sapply(df[c('x', 'x1')], function(x) x %in% boxplot(x)$out)
df[!rowSums(is.outlier),]

#   x x1 z
# 2 1  1 2
# 3 2  2 3
# 4 3  3 4
# 5 4  4 5
# 6 5  5 6
# 7 6  6 7

tidyverse(相同的结果)

library(tidyverse)
df %>% 
  filter(map(list(x, x1), ~!.x %in% boxplot(.x)$out) %>% pmap_lgl(`&`))

你可以试试

z[!((x1 %in% bx1$out) | (x %in% bx$out))]

或者tidyverse

library(tidyverse)
data.frame(x, x1, z) %>% 
  select(starts_with("x")) %>%  
  map_dfr(~.x %in% boxplot(.x, plot = F)$out) %>%  
  with(.,!rowSums(.)) %>% 
  filter(df, .)
   x x1 z
1 50  1 2
2  1  2 3
3  2  3 4
4  3  4 5
5  4  5 6
6  5  6 7