0

site is my data, and I would like to derive trip and seq.

library(data.table)

dt <- data.table(site=c("A", "A", "B", "B", "B", "A", "A", "C", "B"), 
                 trip=c(1,1,2,2,2,3,3,4,5), 
                 seq =c(1,2,1,2,3,1,2,1,1)) 
www
  • 38,575
  • 12
  • 48
  • 84
Tse Lert
  • 192
  • 5
  • `trip` can be derived from [Increment by 1 for every change in column](https://stackoverflow.com/questions/29661269/increment-by-1-for-every-change-in-column) while `seq` can be derived from [Creating a counting variable that restarts at 1 in R](https://stackoverflow.com/questions/34449102/creating-a-counting-variable-that-restarts-at-1-in-r) – Ronak Shah Jan 02 '18 at 08:23
  • 2
    Possible duplicate of [Increment by 1 for every change in column](https://stackoverflow.com/questions/29661269/increment-by-1-for-every-change-in-column) and [Creating a counting variable that restarts at 1 in R](https://stackoverflow.com/questions/34449102/creating-a-counting-variable-that-restarts-at-1) – Ronak Shah Jan 02 '18 at 08:26

1 Answers1

1

You could use rleid():

dt[,trip:=rleid(site)][,seq:=1:.N, "trip"]
mtoto
  • 23,919
  • 4
  • 58
  • 71