In my dataset, i must delete outliers for each group separately.
Here my dataset
vpg=structure(list(customer = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L), code = c(2L, 2L, 3L, 3L, 4L, 4L,
5L, 5L, 2L, 2L, 3L, 3L, 4L, 4L, 5L, 5L), year = c(2017L, 2017L,
2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L), stuff = c(10L, 20L, 30L,
40L, 50L, 60L, 70L, 80L, 10L, 20L, 30L, 40L, 50L, 60L, 70L, 80L
), action = c(0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L,
0L, 1L, 0L, 1L)), .Names = c("customer", "code", "year", "stuff",
"action"), class = "data.frame", row.names = c(NA, -16L))
I must delete outlier from stuff variable, but separately by group customer+code+year
i found this pretty function
remove_outliers <- function(x, na.rm = TRUE, ...) {
qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...)
H <- 1.5 * IQR(x, na.rm = na.rm)
y <- x
y[x < (qnt[1] - H)] <- NA
y[x > (qnt[2] + H)] <- NA
y
}
new <- remove_outliers(vpg$stuff)
vpg=cbind(new,vpg)
View(vpg)
But it works for all groups.
How use this function to delete outlier for each group and get clear dataset for next working ?
Note , in this dataset, there is variable action(it tales value 0 and 1). It is not group variable, but outliers must be delete only for ZERO(0)
categories of action variable.
See Question&Answers more detail:
os