问题
Say, i have three columns
x <- c(-10, 1:6, 50)
x1<- c(-20, 1:6, 60)
z<- c(1,2,3,4,5,6,7,8)
check outliers for x
bx <- boxplot(x)
bx$out
check outliers for x1
bx1 <- boxplot(x1)
bx1$out
now we must delete outliers
x <- x[!(x %in% bx$out)]
x
x1 <- x1[!(x1 %in% bx1$out)]
x1
but we have variable Z(nominal) and we must remove observations, which correspond to the outlier of variables x and x1, in our case it is 1 and 8 obs. of Z
How to do it? in output we must have
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
回答1:
Try this solution:
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
Before delete values in x
and x1
you have to save the positions (x_to_remove
and x1_to_remove
) and than use to clean z
.
Your output:
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
回答2:
If you have a dataframe as
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)
You can do this to remove rows with outliers in x
or x1
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
In tidyverse
(same result)
library(tidyverse)
df %>%
filter(map(list(x, x1), ~!.x %in% boxplot(.x)$out) %>% pmap_lgl(`&`))
回答3:
You can try
z[!((x1 %in% bx1$out) | (x %in% bx$out))]
Or a 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
来源:https://stackoverflow.com/questions/50569314/deleting-outlier-in-r-with-account-of-nominal-var