如何根据特定顺序对字符向量进行排序?

时间:2013-06-10 19:09:10

标签: r

我有一个看起来像

的字符向量
c("white","white","blue","green","red","blue","red")

和特定的订单,如

c("red","white","blue","green")

。我想根据第二个向量的顺序对第一个向量进行排序,以获得以下向量:c("red","red","white","white","blue","blue", "green")。 什么是最好的解决方案?

2 个答案:

答案 0 :(得分:22)

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"

答案 1 :(得分:4)

将您的变量设置为具有适当顺序的级别的因子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

如果您真的希望将结果作为字符向量,则可以使用x2 <- as.character(sort(f1))