将日期转换为R中的星期几

问题描述:

我的数据框中有这种格式的日期:

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

"02-July-2015"

我需要将其转换为星期几(即183).像这样:

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.

您可以使用 lubridate 转换为星期几或一年中的某天.

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