mardi 18 mai 2021

R cumsum with if condition

lets say that I have this dataframe

df <-
  data.frame(
    id = seq(1, 8),
    type = c("NEW", "OLD", "OLD", "NEW", "OLD", "NEW", "NEW", "OLD")
  ) 

I'd like to created "segment" for each TYPE OLD group, thus result would be like this - each segment is marked by order number, please note that first two old types have 1 as segment, second segment is marked as 2.

df <-
  data.frame(
    id = seq(1, 8),
    type = c("NEW", "OLD", "OLD", "NEW", "OLD", "OLD", "NEW", "OLD"),
    segment = c(0, 1, 1, 0, 2, 2, 0, 3)
  )

But I'm having problems with achieving this in R. I can create if else for type segment, i guess I need to do it via cumsum function, but I havent found way how.

mutate(
    segment = if_else(type == "NEW", 0, 1)
    )

Aucun commentaire:

Enregistrer un commentaire