as.POSIXct 无法识别日期格式 =“%Y-%W"; [英] as.POSIXct does not recognise date format = "%Y-%W"

查看:28
本文介绍了as.POSIXct 无法识别日期格式 =“%Y-%W";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"))

我想从 data.frame data 创建一个 xts 对象,其中日期保持格式年-周.当我运行代码时,列采用 2016-12-05 的形式,这是不正确的,与我想要实现的目标相去甚远.

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.

推荐答案

这是关于by can one not parse year and month as a date"的准常见问题解答的一个变体:因为日期 是日、月和年.

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"
> 

使用

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

所以 %W 适用于输入和输出,前提是您还提供一天.

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

对于没有日期的输入数据,您可以只添加一个给定的工作日,比如 1:

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"
> 

这篇关于as.POSIXct 无法识别日期格式 =“%Y-%W";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆