0

I have the below dataset

  Week Year 
  1    2019
  2    2019
  1    2020 
  2    2020

I wish to add a column that shows the start date of the week (starting on Sunday)

So, my ideal output would be

  Week Year Date 
  1    2019 06/01/2019
  2    2019 13/01/2019
  1    2020 05/01/2020
  2    2020 12/01/2010

I have tried the below solution

library (lubridate) 
if (df$Year ==2019) {df$Date = parse_date_time(paste(2019, df$Week, 'Sun', sep=" "),'Y/W/a')}
if (df$Year ==2019) {df$Date = parse_date_time(paste(2020, df$Week, 'Sun', sep=" "),'Y/W/a')}

However, I got the warning message that "failed to parse". Any tips would be appreciated

MFR
  • 2,049
  • 3
  • 29
  • 53

1 Answers1

1

You can do this in base R using as.Date itself.

Based on your attempt it seems your locale is English, so you can try :

as.Date(paste(df$Week, df$Year, 'Sun'), '%U %Y %a')
#[1] "2019-01-06" "2019-01-13" "2020-01-05" "2020-01-05"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    for me it produces "NA"s. not sure why – MFR May 10 '20 at 11:15
  • That is strange. It works for me as shown though. Are you sure your locale is English and not anything else? – Ronak Shah May 10 '20 at 11:24
  • Avoid potential locale issues by using `%w` instead ("Weekday as decimal number (0–6, Sunday is 0") (also described in the link I posted) – Henrik May 10 '20 at 11:47