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)
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)
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