3

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?

Sotos
  • 51,121
  • 6
  • 32
  • 66
nexonvantec
  • 572
  • 1
  • 5
  • 18
  • Possibly related to http://r.789695.n4.nabble.com/Convert-201248-to-Year-Week-date-format-in-R-td4654068.html – akrun May 03 '18 at 13:09

2 Answers2

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.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
1

Here a possible approach:

myDate=as.character("2017/02")

Creation of the calendar (yyyy/dd/mm) of indicated year (E.g. 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

Terru_theTerror
  • 4,918
  • 2
  • 20
  • 39