Reorder factor levels by day of the week in R

前端 未结 2 1779
长发绾君心
长发绾君心 2021-02-01 20:16

I have the following data.frame in R:

> daily
        DoW         Duration
1    Friday 14.0000000000000
2    Monday 21.0000000000000
3  Saturday 12.0000000000         


        
相关标签:
2条回答
  • 2021-02-01 21:14

    Instead of a factor, what you want is an Ordered.Factor.

    This line of R code converts your DoW variable to an "Ordered Factor":

    daily$DoW <- ordered(daily$DoW, levels=c("Monday", "Tuesday", "Wednesday", "Thursday", 
    "Friday", "Saturday", "Sunday"))
    

    Now when you use table, plot or any other functions on Dow it will be the order you specified above.

    0 讨论(0)
  • 2021-02-01 21:23

    You need to specify the levels in factor and then use order with indexing:

    daily$DoW <- factor(daily$DoW, levels= c("Sunday", "Monday", 
        "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"))
    
    daily[order(daily$DoW), ]
    
    0 讨论(0)
提交回复
热议问题