nachocab
nachocab

Reputation: 14454

How can I `seq_along` the levels of a factor in R?

Let's say I have this factor

x <- factor(c("b", "b", "a", "a", "a"), levels = c("a", "b"))

I would like to get this vector from the factor

someOperation(x)
# c(4, 5, 1, 2, 3)

This doesn't work:

order(x)
# c(3, 4, 5, 1, 2)

Upvotes: 1

Views: 253

Answers (1)

alistaire
alistaire

Reputation: 43354

rank has an important ties.method parameter that can be set to "first" to gives the ascending indices like you want:

x <- factor(c("b", "b", "a", "a", "a"), levels = c("a", "b"))

rank(x, ties = 'first')
#> [1] 4 5 1 2 3

An equivalent is calling order twice:

order(order(x))
#> [1] 4 5 1 2 3

Upvotes: 3

Related Questions