Notifications
Clear all

Assign group id start from 0 and end with 1 in R

RSS

(@abhijith)
Noble Member
Joined: 2 years ago
帖子:1350
14/05/2021 12:16 pm

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

ID<-c(1,2,3,4,1,2,3)


Quote
(@ganesh)
Noble Member
Joined: 2 years ago
Posts: 1362
14/05/2021 12:19 pm

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:

library(dplyr)

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


ReplyQuote
Share:
Baidu