I have a vector of integers let's say from 1 to 3 (can be more):
x <- sample(1:3, 10, replace=T)
[1] 1 3 1 2 2 1 3 2 3 2
If I sort x
I'll get
sort(x)
[1] 1 1 1 2 2 2 2 3 3 3
But I need 2s to go first, then 1s, then 3s.
[1] 2 2 2 2 1 1 1 3 3 3
So, if I have a vector y = c(2, 1, 3)
, how I can use it for sorting order?
And actually I need not the values itself, but the index of sorted values in original vector, as I get from order
function.
A somewhat convoluted option:
x[order(factor(x,levels = c(2,1,3)))]
or obviously, just the order
call for just the indices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With