How to get a vector of increasing numbers according to a vector of strings in R?

67 views Asked by At

I have this vector of strings (strings_input) which I want to be a vector of numbers like the expected_output.


strings_input <- c("a", "a", "b", "b", "b", "c", "c", "a", "b", "b")

some function:

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

1

There are 1 answers

0
Maël On

Use data.table::rleid:

data.table::rleid(strings_input)
# [1] 1 1 2 2 2 3 3 4 5 5

Or in base R:

with(rle(strings_input), rep(seq(lengths), lengths))
# [1] 1 1 2 2 2 3 3 4 5 5

There is also a dplyr's consecutive_id:

dplyr::consecutive_id(strings_input)
# [1] 1 1 2 2 2 3 3 4 5 5