Search code examples
rdatetransformweekday

Transform "Y-m-w" to date - first Monday of the week


I am trying to convert %Y-%m-%w to the first date of the respective week starting on Monday.

So %Y-%m-%w to %Y-%m-%d

x <- c("2020-09-01", "2020-09-03", "2020-09-04", "2020-09-05")

2020-09-01 -> 2020-08-31
2020-09-03 -> 2020-09-14
2020-09-04 -> 2020-09-21
2020-09-05 -> 2020-09-28

Solution

  • Using lubridate, convert to a date ignoring the week number, so all dates start on 1st. Then add week numbers, finally round down to Monday.

    library(lubridate)
    x <- c("2020-09-01", "2020-09-03", "2020-09-04", "2020-09-05")
    
    x1 <- ymd(paste0(substring(x, 1, 8), "01"))
    # [1] "2020-09-01" "2020-09-01" "2020-09-01" "2020-09-01"
    
    x2 <- as.numeric(substring(x, 9, 10)) - 1
    # [1] 0 2 3 4
    
    x3 <- x1 + weeks(x2)
    # [1] "2020-09-01" "2020-09-15" "2020-09-22" "2020-09-29"
    
    floor_date(x3, unit = "weeks", week_start = 1) #1 represents Monday.
    # [1] "2020-08-31" "2020-09-14" "2020-09-21" "2020-09-28"