Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (50.2k points)

I am having the following dataset:

DT <- data.drame(v1 = c(0,0,0,1,0,0,1))

From that I just wanted to create an ID cumulatively stopped at a value of 1.

The ID should be


1 Answer

0 votes
by (108k points)

You can simply use ave in base R:

with(DT, ave(v1, c(0, cumsum(v1)[-length(v1)]), FUN = seq_along))

#[1] 1 2 3 4 1 2 3

Or if you want in dplyr also you can use the lag() and with that just create groups and you can assign row numbers in each and every group:


DT %>% group_by(gr = lag(cumsum(v1), default = 0)) %>% mutate(ID = row_number())

If you are beginner and want to know more about R programming, then do check out the R programming tutorial

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories