8

Can someone help me with the following:

I have a date, for example: 3-1-2014,

And I would like to convert this to the number 5, because it is a friday.

So 7-1-2014 would be 1, because it is a monday.

Which package/code can do this for me?

Thanks

Peter Lawrence
  • 719
  • 2
  • 10
  • 20
  • 2
    possible duplicate of [Find the day of a week in R](http://stackoverflow.com/questions/9216138/find-the-day-of-a-week-in-r) – jed May 20 '15 at 20:12
  • 1
    i'm pretty sure this is a duplicate, but you can use POSIXlt, in base R to transform a date to a weekday number. `as.POSIXlt('2015-03-01')$wday` – jed May 20 '15 at 20:12

4 Answers4

14

You can do this easily with lubridate although it indexes Sunday as '1'. So since March 1, 2014 was a Saturday it would return '7'

library(lubridate)
wday(mdy("3-1-2014"))
[1] 7
cdeterman
  • 19,630
  • 7
  • 76
  • 100
8

Using R base, you can use strftime function with "%u" format parameter to return the weekday.

as.numeric(strftime(as.Date('3-1-2014', "%d-%m-%Y"), "%u"))
[1] 5
josep maria porrà
  • 1,198
  • 10
  • 18
2

Now you can use week_start option with wday()

day on which week starts following ISO conventions - 1 means Monday, 7 means Sunday (default). You can set lubridate.week.start option to control this parameter globally.

So following code gives desired output

library(lubridate) 
lubridate::wday(mdy("3-1-2014"), week_start = 1)
[1] 6

Please note that data.table library has function with the same name wday() but without week_start option.

Yuriy Barvinchenko
  • 1,465
  • 1
  • 12
  • 17
1

Using the package "lubridate" is pretty much the answer. It indexes Sunday as '1' and Saturday as '6', but you can simply shift one day by showing the day of week number of the prior day like this:

library(lubridate) 
wday(mdy("3-1-2014") -1)
[1] 6
YiGinger
  • 11
  • 3