2

I am using R. Say I have the vector x:

x <- c(1, 4, 3, 1, 5, 3, 4, 1, 2, 3)

And I want to count, for each value, the number of times that value has already appeared (or the number of times it appears to the left of that value).

In this example, the output would be:

1, 1, 1, 2, 1, 2, 2, 3, 1, 3

How do you do that?

Dan Lewer
  • 871
  • 5
  • 12

1 Answers1

1

An option with ave i.e. grouped by 'x', get the sequence

ave(seq_along(x), x, FUN = seq_along)
#[1] 1 1 1 2 1 2 2 3 1 3

Or using rowid from data.table

library(data.table)
rowid(x)
akrun
  • 874,273
  • 37
  • 540
  • 662