Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 647
PAC Avatar asked Jun 10 '13 19:06

PAC


People also ask

How do I sort a character vector in R?

To sort a vector in R programming, call sort() function and pass the vector as argument to this function. sort() function returns the sorted vector in increasing order. The default sorting order is increasing order. We may sort in decreasing order using rev() function on the output returned by sort().

What is character sort?

Traditionally, information is displayed in sorted order to enable users to easily find the items they are looking for. However, users of different languages might have very different expectations of what a sorted list should look like.

How can I sort the rows of a data frame in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.


1 Answers

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" 
like image 105
Matthew Plourde Avatar answered Oct 05 '22 23:10

Matthew Plourde