我有一个看起来像的字符向量
c("white","white","blue","green","red","blue","red")
和一个特定的订单,就像
c("red","white","blue","green")
. 我想根据第二个向量的顺序对第一个向量进行排序,以获得以下向量:c("red","red","white","white","blue","blue", "green")
。什么是最好的解决方案?
我有一个看起来像的字符向量
c("white","white","blue","green","red","blue","red")
和一个特定的订单,就像
c("red","white","blue","green")
. 我想根据第二个向量的顺序对第一个向量进行排序,以获得以下向量:c("red","red","white","white","blue","blue", "green")
。什么是最好的解决方案?
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"
使您的变量成为具有适当顺序的水平的因子,并且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))
如果您真的希望将结果作为字符向量,您可以使用...