How to sort a vector in increasing order that contains numbers and characters in R?

R ProgrammingServer Side ProgrammingProgramming

A vector can contain numbers, characters or both. The sorting of vectors that contain only numbers or only characters is not very difficult but if a vector contains both of them then it is a little tedious task. In R, we can sort a vector that contains numbers as well as characters with the help of order function but before doing this sorting we must look at the vector very carefully to check if the characters are different for the elements of the vector or not, if they are different then we can’t do this sorting in the manner explained here.


> 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<-
> x10
[1] "121RT167" "121RT123" "121RT149" "121RT198" "121RT126" "121RT158"
[8] "121RT147"
> x10[order(nchar(x10),x10)]
[1] "121RT123" "121RT126" "121RT147" "121RT149" "121RT158" "121RT167"
[8] "RT121146"
Updated on 04-Sep-2020 07:35:05