Christina
Christina

Reputation: 75

assign number every time an event occurs in r

I have this data:

t <- c(NA,NA,NA,1,NA,NA,NA,NA,1,NA,1)
dt <- data.table(t)

     t
 1: NA
 2: NA
 3: NA
 4:  1
 5: NA
 6: NA
 7: NA
 8: NA
 9:  1
10: NA
11:  1

Is it possible to create new column z and assign a number in ascending order every time a 1 occurs in the t column, to get this:

     t  z
 1: NA NA
 2: NA NA
 3: NA NA
 4:  1  1
 5: NA NA
 6: NA NA
 7: NA NA
 8: NA NA
 9:  1  2
10: NA NA
11:  1  3

Thank you

Upvotes: 1

Views: 233

Answers (3)

Mateusz1981
Mateusz1981

Reputation: 1867

with

library(dplyr)

df <- data.frame(t = c(1, NA, 1, NA, 1, NA, NA)) df %>% group_by(t) %>% mutate(z = cumsum(t))

Upvotes: 0

Slug Pue
Slug Pue

Reputation: 256

subset on t==1 and take cumulative sum

  dt[t==1, z := cumsum(t)]

Upvotes: 1

akrun
akrun

Reputation: 887251

We can create a logical index of non-NA elements in 'i' and assign ('z') as the sequence of 't'

dt[!is.na(t), z := seq_along(t)]
dt
#     t  z
# 1: NA NA
# 2: NA NA
# 3: NA NA
# 4:  1  1
# 5: NA NA
# 6: NA NA
# 7: NA NA
# 8: NA NA
# 9:  1  2
#10: NA NA
#11:  1  3

Upvotes: 3

Related Questions