0

I'm trying to create an indexed vector based on another vector. Here is the source vector:

a <- c("A", "A", "B", "C", "D", "E", "E", "E")

and the resulting indexing vector should look like this:

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

I tried this, but this does not produce the correct result:

a <- c("A", "A", "B", "C", "D", "E", "E", "E")
rle.a <- rle(a)
m <- max(rle.a$lengths)
rep(1:m, each=rle.a$lengths)

How to proceed?

jrara
  • 16,239
  • 33
  • 89
  • 120

1 Answers1

0

I found the solution:

a <- c("A", "A", "B", "C", "D", "E", "E", "E")
rle.a <- rle(a)
sequence(rle.a$lengths)
jrara
  • 16,239
  • 33
  • 89
  • 120
  • See, also, this `ave(a, a, FUN = seq_along)` – alexis_laz Apr 17 '14 at 10:13
  • The two approaches are slightly different, the `ave` one will make `c("a","b","a")` into c(1,2,2) - the final element of the original is the second global occurence of 'a' - but the `rle` approach will give `c(1,2,1)` as the final element is the first element of it's own run/ – Gavin Kelly Apr 17 '14 at 11:58
  • @jrara, you can accept your own answer too, to show that the question has been resolved. – A5C1D2H2I1M1N2O1R2T1 Apr 17 '14 at 18:01