简体   繁体   中英

Increasingly count the number of times that a certain condition is met (R)

I would like to know how to increasingly count the number of times that a column in my data.frame satisfies a condition. Let's consider a data.frame such as:

x hour count
1    0    NA
2    1    NA
3    2    NA
4    3    NA
5    0    NA
6    1    NA
...

I would like to have this output:

x hour count
1    0     1
2    1    NA
3    2    NA
4    3    NA
5    0     2
6    1    NA
...

With the count column increasing by 1 everytime the condition hour==0 is met. Is there a smart and efficient way to perform this? Thanks

You can use seq_along on the rows where hour == 0 .

i <- x$hour == 0
x$count[i] <- seq_along(i)
x
#  x hour count
#1 1    0     1
#2 2    1    NA
#3 3    2    NA
#4 4    3    NA
#5 5    0     2
#6 6    1    NA

Data:

x <- structure(list(x = 1:6, hour = c(0L, 1L, 2L, 3L, 0L, 1L), count = c(NA, 
NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, 
-6L))

You can use cumsum to count incremental number of 0 occurrences and replace counts where hour values is not 0 to NA .

library(dplyr)
df %>%
  mutate(count = cumsum(hour == 0), 
         count = replace(count, hour != 0 , NA))

#  x hour count
#1 1    0     1
#2 2    1    NA
#3 3    2    NA
#4 4    3    NA
#5 5    0     2
#6 6    1    NA

data

df <- structure(list(x = 1:6, hour = c(0L, 1L, 2L, 3L, 0L, 1L)), 
class = "data.frame", row.names = c(NA, -6L))

Using data.table

library(data.table)
setDT(df)[hour == 0, count := seq_len(.N)]
df
#   x hour count
#1: 1    0     1
#2: 2    1    NA
#3: 3    2    NA
#4: 4    3    NA
#5: 5    0     2
#6: 6    1    NA

data

df <- structure(list(x = 1:6, hour = c(0L, 1L, 2L, 3L, 0L, 1L)), 
class = "data.frame", row.names = c(NA, -6L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM