4

If I have a vector of numbers in R.

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

I want to return a vector that provides the number of times that value has occurred cumulatively along the vector. I.e.

results <- c(1,2, 1,2,3, 1,2, 1,2,3,4, 3)
falcs
  • 499
  • 2
  • 8
  • 25
  • 7
    [Numbering rows within groups in a data frame](https://stackoverflow.com/questions/12925063/numbering-rows-within-groups-in-a-data-frame). – Henrik Nov 15 '17 at 14:48
  • 1
    As posted in the link to henrik's comment, `data.table::rowid(numbers)` also returns the desired result. – lmo Nov 15 '17 at 14:59

1 Answers1

10

We can use ave and apply the seq_along by grouping with the 'numbers' vector

ave(numbers, numbers, FUN = seq_along)
#[1] 1 2 1 2 3 1 2 1 2 3 4 3
akrun
  • 874,273
  • 37
  • 540
  • 662