我遇到了问题:“ 遇到0时将重置的累积和]通过https://stackoverflow.com/a/32502162/13269143,部分但不是全部地回答了我的问题。我首先想创建一个列,该列逐行累加列b中每个序列的值,这些值之间用0隔开。这是通过使用以下代码实现的:
setDT(df)[, whatiwant := cumsum(b), by = rleid(b == 0L)]
如https://stackoverflow.com/a/32502162/13269143中所建议(提供的其他解决方案对我不起作用。它们仅产生NA值。)现在,我也希望在图中创建第三列“ 我想要的”,该列将给定序列的累加值的最大合计值分配给该特定序列中的每个观察值。让我说明一下,
b Accumulated What I Want
1 1 3
1 2 3
1 3 3
0 0 0
1 1 4
1 2 4
1 3 4
1 4 4
0 0 0
0 0 0
0 0 0
1 1 2
1 2 2
可能有一种非常简单的方法来执行此操作。先感谢您。
您可以像使用rle
和inverse.rle
:
b <- c(1,1,1,0,1,1,1,1,0,0,0,1,1)
x <- rle(b)
i <- x$values == 1
x$values[i] <- x$lengths[i]
inverse.rle(x)
# [1] 3 3 3 0 4 4 4 4 0 0 0 2 2
您可以尝试使用max
代替cumsum
:
library(data.table)
setDT(df)[, whatiwant := max(Accumulated), by = rleid(b == 0L)]
df
# b Accumulated whatiwant
# 1: 1 1 3
# 2: 1 2 3
# 3: 1 3 3
# 4: 0 0 0
# 5: 1 1 4
# 6: 1 2 4
# 7: 1 3 4
# 8: 1 4 4
# 9: 0 0 0
#10: 0 0 0
#11: 0 0 0
#12: 1 1 2
#13: 1 2 2
您可以使用rle()
函数获取游程长度,然后使用mapply()
将其返回值转换为所需的向量:
d <- tibble(b=c(1,1,1,0,1,1,1,1,0,0,0,1,1),
WhatIWant=unlist(mapply(rep, rle(b)$lengths, rle(b)$lengths))) %>%
mutate(WhatIWant=ifelse(b == 0, 0, WhatIWant))
送礼
# A tibble: 13 x 2
b WhatIWant
<dbl> <dbl>
1 1 3
2 1 3
3 1 3
4 0 0
5 1 4
6 1 4
7 1 4
8 1 4
9 0 0
10 0 0
11 0 0
12 1 2
13 1 2