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.
Question : How do I need to change as.POSIXct(myDate,format="%Y/%U")
in order to make it work as described above?
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.
Here a possible approach:
myDate=as.character("2017/02")
Creation of the calendar (yyyy/dd/mm) of indicated year (Eg 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.