Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R increment by 1 for every change in value column and restart the counter

Tags:

r

I would like to find a way to do very similar to this question. Increment by 1 for every change in column

But i want to restart the counter when var1 = c using df$var2 <- with(rle(as.character(df$var1)), rep(seq_along(values), lengths))*

results in column var 2

var1 var2 Should be
   a    1   1
   a    1   1
   1    2   2
   0    3   3
   b    4   4
   b    4   4
   b    4   4
   c    5   1
   1    6   2
   1    6   2
like image 621
Slubee Avatar asked Nov 28 '25 23:11

Slubee


1 Answers

In data.table you can use rleid to get a run-length-id for var1 within each group.

library(data.table)

setDT(df)
df[, var2 := rleid(var1), by = cumsum(var1 == "c")]
df

#    var1 var2
# 1:    a    1
# 2:    a    1
# 3:    1    2
# 4:    0    3
# 5:    b    4
# 6:    b    4
# 7:    b    4
# 8:    c    1
# 9:    1    2
#10:    1    2

and using dplyr

library(dplyr)

df %>%
  group_by(group = cumsum(var1 == "c")) %>%
  mutate(var2 = cumsum(var1 != lag(var1, default = first(var1))) + 1)

data

df <- structure(list(var1 = structure(c(3L, 3L, 2L, 1L, 4L, 4L, 4L, 
5L, 2L, 2L), .Label = c("0", "1", "a", "b", "c"), class = "factor")), 
class = "data.frame", row.names = c(NA, -10L))
like image 99
Ronak Shah Avatar answered Nov 30 '25 16:11

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!