在R中以数字方式对列进行排序

时间:2019-05-08 14:59:44

标签: r string sorting

我的数据如下所示,不同的是数字不正确:

dat<-
paste("Experience",1:20,sep="_")

基本上,我正在尝试根据结尾数字对数字列进行排序,以按照上面的代码生成的顺序对它们进行排序。但是,当我sort的值时,它是根据第一个数字排序的:

"Experience_1"  "Experience_10"  "Experience_11" "Experience_12" 
"Experience_13" "Experience_14"  "Experience_15" "Experience_16" 
"Experience_17" "Experience_18" "Experience_19" "Experience_2" 
"Experience_20" "Experience_3"  "Experience_4"  "Experience_5" 
"Experience_6"  "Experience_7" "Experience_8"  "Experience_9"

有想法吗?

2 个答案:

答案 0 :(得分:3)

Stringr库具有str_sort,它可以

library(stringr)
str_sort(dat, numeric = TRUE)

答案 1 :(得分:2)

一个选项是mixedsort中的gtools

gtools::mixedsort(dat)
#[1] "Experience_1"  "Experience_2"  "Experience_3"  "Experience_4"  "Experience_5"  "Experience_6" 
#[7] "Experience_7"  "Experience_8"  "Experience_9"  "Experience_10" "Experience_11" "Experience_12"
#[13] "Experience_13" "Experience_14" "Experience_15" "Experience_16" "Experience_17" "Experience_18"
#[19] "Experience_19" "Experience_20"