gpt4 book ai didi

在 R 中将 cumsum 值重置为零

转载 作者:行者123 更新时间:2023-12-04 11:40:34 26 4
gpt4 key购买 nike

我有个问题。例如我有这个:

id  truth count
1 1 1
2 1 2
3 0 0
4 1 1
5 1 2
6 1 3
8 0 0

我试过这个:
fun <- rle(df$truth)

df$count <- unlist(sapply(fun$lengths, function(x) {return(1:x)}))

但它不起作用。

最佳答案

这是一个方法。基于 ave :

transform(dat, count = truth * ave(truth, c(0L, cumsum(diff(truth) != 0)), 
FUN = seq_along))

哪里 dat是您的数据框的名称。

关于在 R 中将 cumsum 值重置为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21581451/

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