as.POSIXct does not recognise date format = “%Y-%W”

亡梦爱人 提交于 2019-12-20 04:34:33

问题


library(xts)

data <- data.frame(year_week = c("2016-46", "2016-47", "2016-48"),
                   satisfaction = c(0.25, 0.45, 0.58))

data = xts(data[-1], order.by = as.POSIXct(data$year_week, format = "%Y-%W"))

I want to create an xts object from the data.frame data where the dates keep the format year-week. When I am running the code the columns take the form 2016-12-05 which is incorrect and far from what I am trying to achieve.


回答1:


This is a variant on a quasi-FAQ on 'by can one not parse year and month as a date': because a date is day and month and year.

Or year, a year and week and day. Otherwise you are indeterminate:

> as.Date(format(Sys.Date(), "%Y-%W-%d"), "%Y-%W-%d")
[1] "2017-12-04"
> 

using

> Sys.Date()
[1] "2017-12-04"
> format(Sys.Date(), "%Y-%W-%d")
[1] "2017-49-04"
> 

so %W works on input and output provided you also supply a day.

For input data that does not have a day, you could just add a given weekday, say 1:

> as.Date(paste0(c("2016-46", "2016-47", "2016-48"), "-1"), "%Y-%W-%w")
[1] "2016-11-14" "2016-11-21" "2016-11-28"
> 


来源:https://stackoverflow.com/questions/47644785/as-posixct-does-not-recognise-date-format-y-w

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!