Question

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?

Was it helpful?

Solution

I found the solution:

a <- c("A", "A", "B", "C", "D", "E", "E", "E")
rle.a <- rle(a)
sequence(rle.a$lengths)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top