For each date, get the week of the year to which it belongs, formatting it with format() using %U for %W format placeholders. %U treats Sunday as the first day of the week, while %W considers Monday the first day of the week. Here is an example:
now <- as.Date(Sys.time()) dates <- seq(now, now + 25, by = "1 day") dat <- data.frame(Dates = dates, Week = format(dates, format = "%W")) head(dat, 10)
What gives:
> head(dat, 10) Dates Week 1 2011-11-06 44 2 2011-11-07 45 3 2011-11-08 45 4 2011-11-09 45 5 2011-11-10 45 6 2011-11-11 45 7 2011-11-12 45 8 2011-11-13 45 9 2011-11-14 46 10 2011-11-15 46
Although it is not clear from your question what exactly you want to do, the way to map this date vector (well, my dat data frame is higher) is via merge() . Say we have a vector of weeks that we want to map, and some related data in the weekdat data weekdat :
weekdat <- data.frame(Week = 44:50, Price = c(10, 20, 25, 30, 20, 15, 10))
Then we can bind dat with weekdat using merge() as follows:
> merge(dat, weekdat) Week Dates Price 1 44 2011-11-06 10 2 45 2011-11-07 20 3 45 2011-11-08 20 4 45 2011-11-09 20 5 45 2011-11-10 20 6 45 2011-11-11 20 7 45 2011-11-12 20 8 45 2011-11-13 20 9 46 2011-11-14 25 10 46 2011-11-15 25 11 46 2011-11-16 25 12 46 2011-11-17 25 13 46 2011-11-18 25 14 46 2011-11-19 25 15 46 2011-11-20 25 16 47 2011-11-21 30 17 47 2011-11-22 30 18 47 2011-11-23 30 19 47 2011-11-24 30 20 47 2011-11-25 30 21 47 2011-11-26 30 22 47 2011-11-27 30 23 48 2011-11-28 20 24 48 2011-11-29 20 25 48 2011-11-30 20 26 48 2011-12-01 20
There are other ways to match dates or bind dates to weeks, but the above should give you something to work.
Gavin simpson
source share