How to order characters in a data frame in R to be numerical?

302 views Asked by At

I am trying to make a plot in R in ggplot2 where the X axis is numbers as characters. (As if they were A,B,C etc...) but since they are considered character values the numbers plot in the order 1,10,11....2,20... etc instead of 1,2,3... I was wondering if there was a way to keep the numbers in character class while making them also be in numerical order. Thank you!

1

There are 1 answers

0
Alexey Ferapontov On

Can be done via two class "casts":

> a = c("1","20","10","11","3")
> b = as.character(sort(as.numeric(a)))
> class(b)
[1] "character"
> b
[1] "1"  "3"  "10" "11" "20"