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")才能让它像上面描述的那样工作?
2 个解决方案
#1
2
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选项。
#2
1
Here a possible approach:
这里的一个可能的方法:
myDate=as.character("2017/02")
Creation of the calendar (yyyy/dd/mm) of indicated year (E.g. 2017)
指定年份的日历(yyyyy /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
在这个例子中,星期从星期一开始
#1
2
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选项。
#2
1
Here a possible approach:
这里的一个可能的方法:
myDate=as.character("2017/02")
Creation of the calendar (yyyy/dd/mm) of indicated year (E.g. 2017)
指定年份的日历(yyyyy /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
在这个例子中,星期从星期一开始