如何对R中包含数字和字符的向量进行升序排序?

向量可以包含数字,字符或两者。仅包含数字或仅包含字符的向量的排序不是很困难,但是如果向量包含两个数字和字符,那么这将是一项繁琐的工作。在R中,我们可以使用order函数对包含数字和字符的向量进行排序,但是在进行这种排序之前,我们必须非常仔细地查看向量,以检查向量元素中的字符是否不同,如果它们不同,则无法按照此处说明的方式进行排序。

例子

> x1<-c("S1","S4","S9","S8","S7","S5","S3","S2")
> x1
[1] "S1" "S4" "S9" "S8" "S7" "S5" "S3" "S2"
> x1[order(nchar(x1),x1)]
[1] "S1" "S2" "S3" "S4" "S5" "S7" "S8" "S9"
> x2<-c("S147","S144","S119","S148","S137","S185","S143","S122")
> x2
[1] "S147" "S144" "S119" "S148" "S137" "S185" "S143" "S122"
> x2[order(nchar(x2),x2)]
[1] "S119" "S122" "S137" "S143" "S144" "S147" "S148" "S185"
> x3<-c("167S","123S","149S","198S","126S","158S","146S","147S")
> x3
[1] "167S" "123S" "149S" "198S" "126S" "158S" "146S" "147S"
> x3[order(nchar(x3),x3)]
[1] "123S" "126S" "146S" "147S" "149S" "158S" "167S" "198S"
> x4<-c("167-S","123-S","149-S","198-S","126-S","158-S","146-S","147-S")
> x4
[1] "167-S" "123-S" "149-S" "198-S" "126-S" "158-S" "146-S" "147-S"
> x4[order(nchar(x4),x4)]
[1] "123-S" "126-S" "146-S" "147-S" "149-S" "158-S" "167-S" "198-S"
> x5<-c("167/S","123/S","149/S","198/S","126/S","158/S","146/S","147/S")
> x5
[1] "167/S" "123/S" "149/S" "198/S" "126/S" "158/S" "146/S" "147/S"
> x5[order(nchar(x5),x5)]
[1] "123/S" "126/S" "146/S" "147/S" "149/S" "158/S" "167/S" "198/S"
> x6<-c("167:S","123:S","149:S","198:S","126:S","158:S","146:S","147:S")
> x6
[1] "167:S" "123:S" "149:S" "198:S" "126:S" "158:S" "146:S" "147:S"
> x6[order(nchar(x6),x6)]
[1] "123:S" "126:S" "146:S" "147:S" "149:S" "158:S" "167:S" "198:S"
> x7<-c("167'S","123'S","149'S","198'S","126'S","158'S","146'S","147'S")
> x7
[1] "167'S" "123'S" "149'S" "198'S" "126'S" "158'S" "146'S" "147'S"
> x7[order(nchar(x7),x7)]
[1] "123'S" "126'S" "146'S" "147'S" "149'S" "158'S" "167'S" "198'S"
> x8<-c("167AS","123AS","149AS","198AS","126AS","158AS","146AS","147AS")
> x8
[1] "167AS" "123AS" "149AS" "198AS" "126AS" "158AS" "146AS" "147AS"
> x8[order(nchar(x8),x8)]
[1] "123AS" "126AS" "146AS" "147AS" "149AS" "158AS" "167AS" "198AS"
> x9<-c("RT167","RT123","RT149","RT198","RT126","RT158","RT146","RT147")
> x9
[1] "RT167" "RT123" "RT149" "RT198" "RT126" "RT158" "RT146" "RT147"
> x9[order(nchar(x9),x9)]
[1] "RT123" "RT126" "RT146" "RT147" "RT149" "RT158" "RT167" "RT198"
> x10<-
c("121RT167","121RT123","121RT149","121RT198","121RT126","121RT158","RT12
1146","121RT147")
> x10
[1] "121RT167" "121RT123" "121RT149" "121RT198" "121RT126" "121RT158"
"RT121146"
[8] "121RT147"
> x10[order(nchar(x10),x10)]
[1] "121RT123" "121RT126" "121RT147" "121RT149" "121RT158" "121RT167"
"121RT198"
[8] "RT121146"