Search code examples
rdata-manipulationlevels

R data-manipulation month levels


I read my PA.csv into R.
But here is a problem:
Why my month levels order like this?

levels(PA$Month)
 [1] "1"  "10" "11" "12" "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9" 

If I use this data to draw a plot by ggplot2, and x-axis is PA$Month, the graphic can show but the values for each month are misordered.
To be more concise, the plot's order shows 1, 10 , 11, 12, 2, 3,..., 9.
How to figure out this?

$ Month       : Factor w/ 12 levels "1","10","11",..: 1 5 6 7 8 9 10 11 12 2 ...

very appreciate.


Solution

  • exempleDf <- data.frame(month = as.character(c(10:12,1:9)), value= runif(12))
    factor(exempleDf$month)
    library(ggplot2)
    # plot with level in wrong order
    qplot(x = month, y = value, data = exempleDf)
    # a simple way to reorder factor 
    exempleDf$month <- as.factor(as.numeric(exempleDf$month))
    factor(exempleDf$month)
    # plot with level in right order
    qplot(x = month, y = value, data = exempleDf)
    factor(exempleDf$month)