简体   繁体   English

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

[英]Convert date to day-of-week in 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 (ie 183).我需要将其转换为星期几(即 183)。 Something like:类似的东西:

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

But this doesn't understand the format of the dates.但这不理解日期的格式。

You could use lubridate to convert to day of week or day of year.您可以使用lubridate转换为星期几或一年中的某天。

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
day = as.POSIXct("02-July-2015",format="%d-%b-%Y")

# see ?strptime for more information on date-time conversions

# Day of year as decimal number (001–366).
format(day,format="%j")
[1] "183"

#Weekday as a decimal number (1–7, Monday is 1).
format(day,format="%u")    
[1] "4"

This is what anotherFishGuy supposed, plus converting the values to as.numeric so they fit through classifier.这就是anotherFishGuy 所假设的,加上将值转换为as.numeric以便它们适合分类器。

# day <- Sys.time()
as.num.format <- function(day, ...){
   as.numeric(format(day, ...))
}
doy <- as.num.format(day,format="%j")
doy <- as.num.format(day,format="%u")
hour <- as.num.format(day, "%H")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM