Reputation: 5366
I've got a character vector which looks like
c("white","white","blue","green","red","blue","red")
and a specific order which is like
c("red","white","blue","green")
. I would like to sort the first vector according to the order of the second vector in order to obtain the following vector : c("red","red","white","white","blue","blue", "green")
.
What would be the best solution ?
Upvotes: 36
Views: 48598
Reputation: 44614
x <- c("white","white","blue","green","red","blue","red")
y <- c("red","white","blue","green")
x[order(match(x, y))]
# [1] "red" "red" "white" "white" "blue" "blue" "green"
Upvotes: 60
Reputation: 226097
Make your variable into a factor with the levels in the appropriate order and sort()
:
x1 <- c("white","white","blue","green","red","blue","red")
ord <- c("red","white","blue","green")
f1 <- factor(x1,levels=ord)
sort(f1)
## [1] red red white white blue blue green
## Levels: red white blue green
You can use x2 <- as.character(sort(f1))
if you really want the results as a character vector ...
Upvotes: 13