| 1 |
#' Converts date from week notation according to ISO 8601 to standard notation |
| 2 |
#' |
| 3 |
#' This function returns the date of a given weekdate (year, week of the year, day of week according to ISO 8601). |
| 4 |
#' It is the inverse function to \code{date2ISOweek}. |
| 5 |
#' |
| 6 |
#' According to ISO 8601, the year of the week can differ from the calendar year (see the examples). |
| 7 |
#' |
| 8 |
#' @param weekdate A character vector of year, week, and weekday in format "\code{\%Y-W\%V-\%u}" |
| 9 |
#' @return A vector of class \code{Date} |
| 10 |
#' @seealso \code{\link{strptime}} for a description of the date formats and references on ISO 8601. |
| 11 |
#' @export |
| 12 |
#' @importFrom stringr str_detect str_match |
| 13 |
#' @author Uwe Block \email{u.block.mz@@googlemail.com} |
| 14 |
#' @examples |
| 15 |
#' w <- paste("2009-W53", 1:7, sep = "-") |
| 16 |
#' data.frame(weekdate = w, date = ISOweek2date(w)) |
| 17 |
#' # convert from calendar date to week date and back to calendar date |
| 18 |
#' x <- paste(1999:2011, "-12-31", sep = "") |
| 19 |
#' w <- date2ISOweek(x) |
| 20 |
#' d <- ISOweek2date(w) |
| 21 |
#' data.frame(date = x, weekdate = w, date2 = d) |
| 22 |
ISOweek2date <- function(weekdate) { |
| 23 |
kPattern <- "^([0-9]{4})-W([0-9]{2})-([0-9]{1})$" |
| 24 |
# not used kPattern <- "^([0-9]{4})-W([0][1-9]|[1-4][0-9]|[5][0-3])-([1-7]{1})$" |
| 25 |
# instead check ranges separately |
| 26 |
stopifnot(all(is.na(weekdate) | stringr::str_detect(weekdate, kPattern))) |
| 27 |
wd_ywd <- stringr::str_match(weekdate, kPattern) |
| 28 |
# take care of all NA input because this will break the split into 4 columns |
| 29 |
if (all(is.na(weekdate))) { |
| 30 |
return(rep(as.Date(NA_character_), length.out = length(weekdate))) |
| 31 |
} |
| 32 |
stopifnot(ncol(wd_ywd) == 4) |
| 33 |
year <- wd_ywd[, 2] |
| 34 |
week <- as.integer(wd_ywd[, 3]) |
| 35 |
weekday <- as.integer(wd_ywd[, 4]) |
| 36 |
stopifnot(all(is.na(week) | (1 <= week & week <= 53))) |
| 37 |
stopifnot(all(is.na(weekday) | (1 <= weekday & weekday <= 7))) |
| 38 |
# first week of the year includes always the 4th of January, |
| 39 |
# take care of NA dates |
| 40 |
january04 <- as.Date(ifelse(is.na(year), NA, paste(year, "01", "04", sep="-"))) |
| 41 |
# first thursday of the year |
| 42 |
first_thursday <- thursday0(january04) |
| 43 |
# advance by week-1 thursdays |
| 44 |
nearest_thursday <- first_thursday + 7 * (week - 1) |
| 45 |
# correct for weekday |
| 46 |
return(nearest_thursday - 4 + weekday) |
| 47 |
} |