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
CodePudding user response:
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"
CodePudding user response:
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