Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 计算连续发生的次数,并在找到值后立即停止_R_Cumulative Sum - Fatal编程技术网

R 计算连续发生的次数,并在找到值后立即停止

R 计算连续发生的次数,并在找到值后立即停止,r,cumulative-sum,R,Cumulative Sum,我有一个如下所示的数据框: 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

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

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
基本上,我需要从
bin=3
开始计算连续零的数量。但是一旦
count
列为
>0
我希望其余的值为零

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

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
但在找到零后,它们仍在继续计数。

还有其他解决方案吗?

我们可以先创建一个行号列
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
版本的等效基数R为

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

太棒了,我只是想把
base
解决方案翻译成
dplyr
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
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
df$cumCount <- replace(1:nrow(df), cumsum(df$count != 0) > 0, 0)