53rd week of the year in R?
The package ISOweek
manages ISO 8601 style week numberings, converting to and from Date
objects in R
. See ISOweek
for more. Continuing the example dates above, we first need to modify the formatting a bit. They must be in form yyyy-Www-w
rather than yyyy-ww
, i.e. 2009-W53-1
. The final digit identifies which day of the week to use in identifying the week, in this case it is the Monday. The week number must be two-digit.
library(ISOweek)dates <- c("2009-50", "2009-51", "2009-52", "2009-53", "2010-01", "2010-02")other.dates <- c("2007-53", "2008-53", "2009-53", "2010-53")dates <- sub("(\\d{4}-)(\\d{2})", "\\1W\\2-1", dates)other.dates <- sub("(\\d{4}-)(\\d{2})", "\\1W\\2-1", other.dates)## Check:dates# [1] "2009-W50-1" "2009-W51-1" "2009-W52-1" "2009-W53-1" "2010-W01-1"# [6] "2010-W02-1"(iso.date <- ISOweek2date(dates)) # deal correctly# [1] "2009-12-07" "2009-12-14" "2009-12-21" "2009-12-28" "2010-01-04"# [6] "2010-01-11"(iso.other.date <- ISOweek2date(other.dates)) # also deals with this# [1] "2007-12-31" "2008-12-29" "2009-12-28" "2011-01-03"## Check that back-conversion works:all(date2ISOweek(iso.date) == dates)# [1] TRUE## This does not work for the others, since the 53rd week of## e.g. 2008 is back-converted to the first week of 2009, in## line with the ISO 6801 standard.date2ISOweek(iso.other.date) == other.dates# [1] FALSE FALSE TRUE FALSE