r - Substitute outliers depending on quartile and group -
i have following data frame:
d = id group value 1 1 2 2 3 10 4 b 100 5 b 200 6 b 1000 i replace values above 99% quartile na depending on group belong. in example observations (id) 3 , 6. far have piece of code want not depending on each group.
d[ d$value.ta < quantile(d$value, 0.99), 'value'] <- na any help?
you can use group_by() function dplyr:
library(dplyr) d <- d %>% group_by(group) %>% mutate(value.ta = ifelse(value < quantile(value, 0.99), value, na)) %>% ungroup() > d # tibble: 6 x 4 id group value value.ta <int> <fctr> <dbl> <dbl> 1 1 1 1 2 2 2 2 3 3 10 na 4 4 b 100 100 5 5 b 200 200 6 6 b 1000 na data:
d <- data.frame( id = seq(1, 6), group = rep(c("a", "b"), each = 3), value = c(1,2,10,100,200,1000) )
Comments
Post a Comment