Search code examples
rlubridate

Working with weekdays in number format in R lubriday::wday


I am currently working with a dataset that has columns for weekdays in a number format. For weekdays the number one represents Monday and 7 Sunday; preliminarily, I am trying to make use of some sort of library that can convert this numbers into string/text format. For example, if I were to pass the vector days I would like to get the number days as text form.

Input:

days<-c(1,3,5,7)

Desired output:

"monday", "wednesday", "friday", "sunday"

I am using the library lubridate in R when running this line of code I get:

> wday(days,  week_start = getOption("lubridate.week.start", 1), label = TRUE)
[1] Sun Tue Thu Sat
Levels: Mon < Tue < Wed < Thu < Fri < Sat < Sun

Which is not what I want since number 1 must be Mon and 7 Sun and even if I try to change the parameter week_sart to any number, I still get Sun instead of Mon and thus all other days are incorrect.

> wday(days,  week_start = getOption("lubridate.week.start", 7), label = TRUE)
[1] Sun Tue Thu Sat
Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat

So I ended up running this line to get my desired output:

wday(days+1,  week_start = getOption("lubridate.week.start", 1), label = TRUE)
[1] Mon Wed Fri Sun
Levels: Mon < Tue < Wed < Thu < Fri < Sat < Sun

But what I really want to have a function that will set one as mon by default in case I have to work in other machines. How can I properly change the parameters of the  lubridate::wday function to get my desired output?


Solution

  • You can do this efficiently without lubridate, using days as an index vector.

    w <- tolower(weekdays(.Date(4:10)))
    w
    ## [1] "monday"    "tuesday"   "wednesday" "thursday"  "friday"    "saturday"  "sunday"
    
    w[days]
    ## [1] "monday"    "wednesday" "friday"    "sunday" 
    

    If you want a factor, then you can do

    gl(7L, 1L, labels = w)[days]
    ## [1] monday    wednesday friday    sunday   
    ## Levels: monday tuesday wednesday thursday friday saturday sunday
    

    optionally passing ordered = TRUE to gl.

    It's worth mentioning that the weekdays result is locale-dependent. Non-English locales will use non-English names for week days, etc. If you want completely reproducible results, then construct w yourself.

    w <- c("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")