![](/img/trans.png)
[英]How to order a character vector according to a second character vector made up of substrings of the first?
[英]How to sort a character vector according to a specific order?
我有一个看起来像的字符向量
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))
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.