How do you order a nominale variable. e.g month in R?

后端 未结 3 1108
北荒
北荒 2021-01-07 15:12

This is a very basic problem but I do not find an answer. How can I order my variable \"Month\" so that when I make a bar plot January is first, then February...?

Th

相关标签:
3条回答
  • 2021-01-07 16:02

    @PhilipPham's answer is correct: this is equivalent but a little simpler:

    Month <- factor(Month,levels=month.name)
    

    since there is a built-in month.name variable in R that gives the English month names in order.

    0 讨论(0)
  • 2021-01-07 16:04
    df$Month <- factor(df$Month,format(seq(as.Date("2013-01-01"),by="1 month",length=12),"%B"))
    

    Then, plot again.

    0 讨论(0)
  • 2021-01-07 16:13

    Adding to the answer from Ben (since I cannot add comments yet), you can do the following, assuming you have a dataframe with a Month column:

    df$Month <- factor(df$Month,levels=month.name)
    df = df[order(df$Month,decreasing=FALSE),]
    
    0 讨论(0)
提交回复
热议问题