Reputation: 14454
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
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