gpt4 book ai didi

在 R 中按组删除异常值

转载 作者:行者123 更新时间:2023-12-01 22:08:43 24 4
gpt4 key购买 nike

在我的数据集中,我必须分别删除每个组的异常值。这是我的数据集

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))

我必须从 stuff 变量中删除离群值,但按组 customer+code+year 分开

我发现了这个漂亮的函数

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)

但它适用于所有群体。如何使用此功能删除每个组的异常值并为下一步工作获得清晰的数据集?注意,在这个数据集中,有变量 Action (它的值是 0 和 1)。它不是组变量,但必须删除只有 ZERO(0) 类别的 Action 变量的异常值。

最佳答案

这是一个使用 data.table 的解决方案:

library("data.table")
setDT(vpg)
vpg[, new:=stuff][action==0, new:=remove_outliers(stuff), by=.(customer, code, year)]

关于在 R 中按组删除异常值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com