PAC
PAC

Reputation: 5366

How to sort a character vector according to a specific order?

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

Answers (2)

Matthew Plourde
Matthew Plourde

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

Ben Bolker
Ben Bolker

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

Related Questions