Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to day-of-week in R

Tags:

date

r

I have a date in this format in my data frame:

"02-July-2015"

And I need to convert it to the day of the week (i.e. 183). Something like:

df$day_of_week <- weekdays(as.Date(df$date_column))

But this doesn't understand the format of the dates.

like image 480
Cybernetic Avatar asked Dec 25 '22 06:12

Cybernetic


1 Answers

You could use lubridate to convert to day of week or day of year.

library(lubridate)

# "02-July-2015" is Thursday
date_string <- "02-July-2015"
dt <- dmy(date_string)
dt
## [1] "2015-07-02 UTC"

### Day of week : (1-7, Sunday is 1)
wday(dt)
## [1] 5

### Day of year (1-366; for 2015, only 365) 
yday(dt)
## [1] 183

### Or a little shorter to do the same thing for Day of year
yday(dmy("02-July-2015"))
## [1] 183
like image 112
steveb Avatar answered Dec 26 '22 21:12

steveb