计算连续出现并在找到值后停止

count consecutive occurrence and stop once found value

我有一个如下所示的数据框:

account <- c('123','123','123','123')
bin <- c(3,6,9,12)
count <- c(0,0,2,0)

df <- data.frame(account,bin,count)
df
> df
  account bin count
1     123   3     0
2     123   6     0
3     123   9     2
4     123  12     0

我想要这样的输出:

  > df
      account bin count cumCount
    1     123   3     0    1
    2     123   6     0    2
    3     123   9     2    0
    4     123  12     0    0

基本上,我需要统计从bin = 3开始的连续归零的个数。但是一旦 count 列是 >0 我希望其余的值都为零。

我在网上浏览了一下,这里有 2 个部分的解决方案:

df %>% 
  group_by(count) %>% 
  mutate(id = row_number())


# A tibble: 4 x 4
# Groups:   count [2]
  account   bin count    id
   <fctr> <dbl> <dbl> <int>
1     123     3     0     1
2     123     6     0     2
3     123     9     2     1
4     123    12     0     3

   df %>% 
  mutate( x = sequence(rle(
    as.character(count))$lengths))

> df %>% 
+   mutate( x = sequence(rle(
+     as.character(count))$lengths))
  account bin count x
1     123   3     0 1
2     123   6     0 2
3     123   9     2 1
4     123  12     0 1

但他们在找到零后仍然继续计数。
还有其他解决方案吗?

我们可以先创建一个行号列cumCount。之后,我们将索引的值替换为 0,从第一次出现的非零值到数据帧的末尾。

df$cumCount = 1:nrow(df)
df$cumCount[which.max(df$count != 0) : nrow(df)] <- 0

df

#  account bin count cumCount
#1     123   3     0        1
#2     123   6     0        2
#3     123   9     2        0
#4     123  12     0        0

dplyr中,使用row_numberreplace函数更容易

library(dplyr)
df %>%
   mutate(cumCount = replace(row_number(), cumsum(count!=0) > 0, 0))


#  account bin count cumCount
#1     123   3     0        1
#2     123   6     0        2
#3     123   9     2        0
#4     123  12     0        0

上述 dplyr 版本的等价基础 R 将是

df$cumCount <- replace(1:nrow(df), cumsum(df$count != 0) > 0, 0)