0

I've got a Dataset that looks like this:

Year Week Cases
2010 1 2
2010 4 3
2010 5 5
2010 6 1

I would like to convert the Year-Week columns into a single timestamp column (dd/mm/yyyy). Day of the week could be the first or the last one.
Is there a simple way to solve this?

Best, Daniel

Daniel AG
  • 47
  • 7
  • 1
    Checking this thread might get you there: https://stackoverflow.com/questions/32470414/convert-week-number-to-date – mabreitling May 27 '22 at 11:44

2 Answers2

1

The weeks function in lubridate and str_c function in stringr might provide it:

df <- tribble(~year, ~week, 2010,1,2010,4,2010,5,2010,6)

df_tbl <- df %>% 
  mutate(beg = ymd(str_c(year, "-01-01")),
         date_var = beg + weeks(week))

df_tbl$date_var    

  • This works. Note that `stringr::str_c()` could just as easily be replaced with `base::paste()` – Captain Hat May 27 '22 at 12:48
  • `weeks()` and `ymd()` are both part of the `lubridate` package, which could be clearer in the example. This code will `require(lubridate)` and `require(dplyr)` to run. – Captain Hat May 27 '22 at 12:50
0

If you count week 1 as starting on 1st January, you could do:

as.Date(paste(df$Year, 1, 1, sep = '-')) + 7 * (df$Week - 1)
#> [1] "2010-01-01" "2010-01-22" "2010-01-29" "2010-02-05"

If you count week 1 as starting on the first Monday of the year (as per ISO 8601) then you could use this little function:

year_week <- function(year, week) {
  as.Date(unlist((Map(function(y, w) {
    d <- which(lubridate::wday(as.Date(paste(y, 1, 1:7, sep = '-'))) == 2)
    as.Date(paste(y, 1, d, sep = '-')) + (w - 1) * 7}, y = year, w = week))),
    origin = '1970-01-01')
}

This will give you the date of the nth Monday in the year, so that we have:

year_week(df$Year, df$Week)
#> [1] "2010-01-04" "2010-01-25" "2010-02-01" "2010-02-08"
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87