Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 210
Peter Lawrence Avatar asked May 20 '15 20:05

Peter Lawrence


People also ask

How do you convert a date into a day of the week in R?

Method 1: Using weekdays() function. In this method we're converting date to day of the week, the user needs to call the weekdays() function which is an in-build function in R language and pass the vectors of the date into it. By doing this it will be returning the weekdays of every given date to the user.

How do I convert a date to a number in R?

Method 1: Use as.numeric() as. This will return the number of seconds that have passed between your date object and 1/1/1970.

How do I get the day of a date in R?

weekdays() function in R Language is used to find out a day on a specific date and return as a string.

How do I change date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.


2 Answers

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
like image 153
cdeterman Avatar answered Oct 20 '22 18:10

cdeterman


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
like image 45
josep maria porrà Avatar answered Oct 20 '22 19:10

josep maria porrà