Lisa Clark
Lisa Clark

Reputation: 340

Order a data table alphanumerically by alphabet then numeric values in R

I have a data table in R and I wish to sort a single column by values alphabetically and then numerically.

For example, the column may have similar entries to:

v1<- c("All", "1.2 - Social Care", "2.1 - Science", "1.1 - Health")

Using the order function

v1[order(v1)]

leads to

[1] "1.1 - Health"      "1.2 - Social Care" "2.1 - Science"     "All"

However, what I want is:

"All"     "1.1 - Health"    "1.2 - Social Care"    "2.1 - Science"

How can I sort by alphabet before numerics?

Upvotes: 2

Views: 544

Answers (3)

Frank
Frank

Reputation: 66819

You can use a regex to identify which entries start with a number and put them last:

w = grep("^[0-9]", v1)
c(sort(v1[-w]), sort(v1[w]))
# "All"               "1.1 - Health"      "1.2 - Social Care" "2.1 - Science" 

For more on regex in R, type ?regex and ?grep. Alternately, you could construct w = which(substr(v1,1,1) %in% 0:9), similar to @MikeyMike's answer.

Upvotes: 2

Mike H.
Mike H.

Reputation: 14360

Another way to do it would be to directly use the order function to first sort on whether or not the first character of the string is numeric and then sort as you normally would on v1.

v1[order(-grepl("[[:alpha:]]", substr(v1,1,1)), v1)]

[1] "All"               "1.1 - Health"      "1.2 - Social Care" "2.1 - Science"  

Upvotes: 0

lmo
lmo

Reputation: 38500

Another method would be to add "0 - " in front of entries that begin with a letter:

v1[grep("^[a-zA-Z]", v1)] <- paste0("0 - ", v1[grep("^[a-zA-Z]", v1)])

sort(v1)
[1] "0 - All"           "1.1 - Health"      "1.2 - Social Care" "2.1 - Science"

Upvotes: 0

Related Questions