| 1 |
#' Week of the year according to ISO 8601 |
| 2 |
#' |
| 3 |
#' This function returns the year and the week of the year of a given date according to ISO 8601. |
| 4 |
#' It is an substitute for the \code{\%Y-W\%V} format which is not implemented on Windows. |
| 5 |
#' |
| 6 |
#' According to ISO 8601, the year of the week can differ from the calendar year (see the examples). |
| 7 |
#' |
| 8 |
#' @param date Vector which can be coerced to class \code{Date} |
| 9 |
#' @return A character vector of year and week in format "\code{\%Y-W\%V}" |
| 10 |
#' @seealso \code{\link{strptime}} for a description of the date formats and references on ISO 8601. |
| 11 |
#' \code{\link[surveillance]{isoWeekYear}} for an alternative implementation. |
| 12 |
#' @export |
| 13 |
#' @author Hatto von Hatzfeld \email{hatto@@salesianer.de}, |
| 14 |
#' adopted to \R by Uwe Block \email{u.block.mz@@googlemail.com} |
| 15 |
#' @references \url{http://www.salesianer.de/util/kalwoch.html} |
| 16 |
#' @examples |
| 17 |
#' x <- paste(1999:2011, "-12-31", sep = "") |
| 18 |
#' y <- as.Date(x) |
| 19 |
#' data.frame(date = format(y), week = ISOweek(y)) |
| 20 |
#' data.frame(date = x, week = ISOweek(x)) |
| 21 |
ISOweek <- function(date) { |
| 22 |
date <- as.Date(date) |
| 23 |
nearest_thursday <- thursday0(date) |
| 24 |
year <- year0(nearest_thursday) # year of the week can differ from year of the date |
| 25 |
# first week of the year includes always the 4th of January, |
| 26 |
# take care of NA dates |
| 27 |
january04 <- as.Date(ifelse(is.na(year), NA, paste(year, "01", "04", sep="-"))) |
| 28 |
# first thursday of the year |
| 29 |
first_thursday <- thursday0(january04) |
| 30 |
# difference in days, use difftime explicitly to avoid problems with package "lubridate" |
| 31 |
# lubridate overrides + and - methods for POSIXt, Date and difftime |
| 32 |
diffdays <- difftime(nearest_thursday, first_thursday, units = "days") |
| 33 |
stopifnot(class(diffdays) == "difftime") |
| 34 |
# as.integer is required to convert difftime object |
| 35 |
week <- as.integer(diffdays) %/% 7 + 1 |
| 36 |
# use sprintf to produce leading zeros for the week number |
| 37 |
return(ifelse(is.na(week), NA_character_, sprintf("%04.0f-W%02.0f", year, week))) |
| 38 |
} |
| 39 |
|