Peter Lawrence
Peter Lawrence

Reputation: 749

Convert a date to a day number (monday = 1, tuesday = 2) in R

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

Upvotes: 8

Views: 20794

Answers (4)

Yuriy Barvinchenko
Yuriy Barvinchenko

Reputation: 1595

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.

Upvotes: 2

josep maria porrà
josep maria porrà

Reputation: 1388

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

Upvotes: 8

YiGinger
YiGinger

Reputation: 11

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

Upvotes: 1

cdeterman
cdeterman

Reputation: 19960

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

Upvotes: 14

Related Questions