我有一个向量,字符类型为数字。
x = c("5","-.5","-.1",".01",".1","1","3")
是否有使用每个字符的数字值对该字符向量进行排序的快速简便的方法?我找不到一种干净的方法来做到这一点。
例如,我想要一个函数
x <- characterOrder(x)
输出:
c("-.5","-.1",".01",".1","1","3", "5")
谢谢!
答案 0 :(得分:3)
通过as.numeric值对它进行排序时,可以使用订购函数和as.numeric在base R中进行此操作。
x = c("5","-.5","-.1",".01",".1","1","3")
x[order(as.numeric(x))]
[1] "-.5" "-.1" ".01" ".1" "1" "3" "5"
如果要在函数中使用此功能:
characterOrder <- function(x) {
return(x[order(as.numeric(x))])
}
答案 1 :(得分:0)
您可以尝试mixedsort
中的gtools
library(gtools)
mixedsort(x)
#[1] "-.5" "-.1" ".01" ".1" "1" "3" "5"