gpt4 book ai didi

r - 遇到 0 时重置的累积和

转载 作者:行者123 更新时间:2023-12-04 01:30:13 26 4
gpt4 key购买 nike

我想对一个字段进行累积总和,但只要遇到 0 就重置聚合值。

这是我想要的一个例子:

data.frame(campaign = letters[1:4] , 
date=c("jan","feb","march","april"),
b = c(1,0,1,1) ,
whatiwant = c(1,0,1,2)
)

campaign date b whatiwant
1 a jan 1 1
2 b feb 0 0
3 c march 1 1
4 d april 1 2

最佳答案

另一个基地只是

with(df, ave(b, cumsum(b == 0), FUN = cumsum))
## [1] 1 0 1 2

这只会分割列 b根据 0 分组出现并计算 b 的累积和每个这些组

使用最新 data.table 的另一种解决方案版本 (v 1.9.6+)
library(data.table) ## v 1.9.6+
setDT(df)[, whatiwant := cumsum(b), by = rleid(b == 0L)]
# campaign date b whatiwant
# 1: a jan 1 1
# 2: b feb 0 0
# 3: c march 1 1
# 4: d april 1 2

每个评论的一些基准
set.seed(123)
x <- sample(0:1e3, 1e7, replace = TRUE)
system.time(res1 <- ave(x, cumsum(x == 0), FUN = cumsum))
# user system elapsed
# 1.54 0.24 1.81
system.time(res2 <- Reduce(function(x, y) if (y == 0) 0 else x+y, x, accumulate=TRUE))
# user system elapsed
# 33.94 0.39 34.85
library(data.table)
system.time(res3 <- data.table(x)[, whatiwant := cumsum(x), by = rleid(x == 0L)])
# user system elapsed
# 0.20 0.00 0.21

identical(res1, as.integer(res2))
## [1] TRUE
identical(res1, res3$whatiwant)
## [1] TRUE

关于r - 遇到 0 时重置的累积和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32501902/

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