[英]How to convert a date as year/week to the first day of the week via POSIXct?
I want to convert 我想转换
myDate=as.character("2017/02")
which is in the format year/week to a date that is the first day of this week. 其格式为年/周至本周第一天的日期。 So I tried:
所以我尝试过:
print(as.POSIXct(myDate,format="%Y/%U"))
However, this gives me 但是,这给了我
[1] "2017-05-03 CEST"
which is certainly not the first day of the second week in 2017. 这肯定不是 2017年第二周的第一天。
Question : How do I need to change as.POSIXct(myDate,format="%Y/%U")
in order to make it work as described above? 问题 :如何更改
as.POSIXct(myDate,format="%Y/%U")
以使其按上述方式工作?
A year and a week is not a proper date. 一年零一周不是合适的日期。 A day would need to be associated with the week.
一天需要与一周相关联。 For example:
例如:
myDate=as.character("2017/02")
as.POSIXct(paste(myDate, "0"),format="%Y/%U %w")
#[1] "2017-01-08 EST"
this assumes the first day of the week is Sunday. 这假设一周的第一天是星期天。 If you prefer a Monday then see the %u option.
如果您更喜欢星期一,请参阅%u选项。
Here a possible approach: 这是一种可能的方法:
myDate=as.character("2017/02")
Creation of the calendar (yyyy/dd/mm) of indicated year (Eg 2017) 创建指定年份的日历(yyyy / dd / mm)(例如2017)
year_date<-seq.Date(as.Date(paste0(substr(myDate,1,4),"/01/01")),as.Date(paste0(substr(myDate,1,4),"/12/31")),by=1)
Using library ISOweek
, this code finds the first day of each week 使用库
ISOweek
,此代码可以找到每周的第一天
library("ISOweek")
first_day<-cumsum(ISOweekday(year_date)==1)
Extraction of the first day of the indicated week 提取指定周的第一天
year_date[which(first_day==as.numeric(unlist(strsplit(myDate,split="/"))[2]))[1]]
[1] "2017-01-09"
NB : in this example weeks start on monday 注意 :在这个例子中,星期一星期几开始
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.