下面的函数根据累积和是否达到某个最大值然后重新开始对向量中的值进行分组。
cs_group <- function(x, threshold) {
cumsum <- 0
group <- 1
result <- numeric()
for (i in 1:length(x)) {
cumsum <- cumsum + x[i]
if (cumsum > threshold) {
group <- group + 1
cumsum <- x[i]
}
result = c(result, group)
}
return (result)
}
例子
示例中的最大值为 10。第一组仅包括 9;因为将它与下一个值相加将导致总和为 12。下一组包括 3、2、2(+8 将导致值高于 10)。
test <- c(9, 3, 2, 2, 8, 5, 4, 9, 1)
cs_group(test, 10)
[1] 1 2 2 2 3 4 4 5 5
但是,我更愿意在每组中包含导致累积总和高于最大值 10 的值。
理想结果:
[1] 1 1 2 2 2 3 3 3 4
最佳答案
您可以编写自己的自定义函数或使用他人编写的代码。
I had the exact same problem几天前,这已包含在 MESS
中包裹。
devtools::install_github("ekstroem/MESS")
MESS::cumsumbinning(test, 10, cutwhenpassed = TRUE)
#[1] 1 1 2 2 2 3 3 3 4
关于r - 按组计算 R 中的累积总和,当组中的值总和大于最大值时重新开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60074932/