3

Assume I have the following vector:

dat <- c(1,1,1, 2,2,2, 3,3, 4,4,4,4)   <- (I added spaces to better see grouping)

I would like to assign sequential numbers starting with 1 restarting for each unique value in dat. The desired result would be:

1 2 3   1 2 3   1 2   1 2 3 4    <- (I added spaces to better see grouping)

My attempt:

unlist(
  lapply(unique(dat), function(x) 
     seq(1,length(which(dat==x)==T),1)
  )
)

[1] 1 2 3 1 2 3 1 2 1 2 3 4

Is there a more straightforward way to do this?

theforestecologist
  • 4,667
  • 5
  • 54
  • 91
  • If there is only one run per value: [Numbering rows within groups in a data frame](https://stackoverflow.com/questions/12925063/numbering-rows-within-groups-in-a-data-frame), else [R: count consecutive occurrences of values in a single column](https://stackoverflow.com/questions/19998836/r-count-consecutive-occurrences-of-values-in-a-single-column) – Henrik Jul 11 '19 at 16:22

1 Answers1

3

Yes:

sequence(rle(dat)$lengths)
joran
  • 169,992
  • 32
  • 429
  • 468