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 ?
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().
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.
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.
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"
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