Combine numeric year and week into date?

Suppose I have data like the following:

my_data <- data.frame(year = sample(c(2018,2019), 100, T), 
                      week = sample(1:52, 100, T))

Is it possible to combine those two columns into a "date" column so I can do operations with that new variable? My guess is that lubridate can do that but I cannot figure it out.

I would do it with something that way, starting from a date and adding N weeks period to it

my_data <- data.frame(year = sample(c(2018,2019), 100, T), 
                      week = sample(1:52, 100, T))

library(lubridate)
#> 
#> Attachement du package : 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
dates <- make_datetime(year = my_data$year) + weeks(my_data$week)
head(dates)
#> [1] "2018-10-01 UTC" "2019-03-26 UTC" "2019-06-11 UTC" "2018-07-02 UTC"
#> [5] "2019-05-28 UTC" "2018-08-20 UTC"

Created on 2019-11-14 by the reprex package (v0.3.0)

Just take care of week numbering and start day of the week maybe.

Does it makes sense ?

Otherwise, when parsing character to date I think there is a %U and %W available to describe week format. Look at strptime or lubridate::parse_date_time

Hope it helps

4 Likes

make_date can be used instead of make_datetime to do that.

my_data <- data.frame(year = sample(c(2018,2019), 100, T), 
                      week = sample(1:52, 100, T))

library(lubridate)
#> 
#> Attachement du package : 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
dates <- make_date(year = my_data$year) + weeks(my_data$week)
head(dates)
#> [1] "2018-04-23" "2019-03-19" "2019-04-02" "2018-02-12" "2018-12-24"
#> [6] "2018-04-16"

Created on 2019-11-14 by the reprex package (v0.3.0)

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

I'd add a pipe

%>% ymd(.)

to ditch the tz