我在R中改变我的df时遇到了麻烦。我的df看起来像这样
df<
I class part datetime value indicator
<int> <chr> <chr> <S3: POSIXct> <dbl> <dbl>
1 1 A part1 2016-12-15 10:43:08 0.12 0
2 1 A part2 2015-11-16 13:52:07 0.15 0
3 1 A part3 2015-11-16 15:37:27 1.20 0
4 2 A part1 2015-11-16 15:43:03 0.78 1
5 2 A part2 2015-11-16 16:01:03 0.14 1
6 2 A part3 2015-11-05 07:10:02 1.40 1
... ... ... ... ... ... ...
我正在尝试删除组指标(0或1)中第1部分的极端异常值
我试过这个
remove_outliers <- function(x, na.rm = TRUE, ...) {
qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...)
H <- 3.0 * IQR(x, na.rm = na.rm)
y <- x
y[x < (qnt[1] - H)] <- NA
y[x > (qnt[2] + H)] <- NA
y
}
dfNew <- df %>%
group_by(indicator, part) %>%
mutate(value = remove_outliers(value[part="part1"])) %>%
ungroup()
这将删除所有值。如何才能删除组指示符中仅有第1部分的极端异常值?
答案 0 :(得分:1)
代码值中的2个错误[part =&#34; part1&#34;]应该有&#34; ==&#34;不是&#34; =&#34;因为值[part ==&#34; part1&#34;]比值短,所以放错了地方。您需要在治疗开始时进行分组
dfNew <- subset(df,part=="part1") %>%
group_by(indicator, part) %>%
mutate(value = remove_outliers(value)) %>%
ungroup()
获取整个数据集而不仅仅是子集
mutate_cond <- function(.data, condition, ..., envir = parent.frame()) {
condition <- eval(substitute(condition), .data, envir)
.data[condition, ] <- .data[condition, ] %>% mutate(...)
.data
}
dfNew =df %>%
group_by(indicator, part) %>%
mutate_cond(part=="part1",value = remove_outliers(value)) %>%
ungroup()
这次修改后它适用于我