How can I group days into weeks?

In R, how can I relate a vector of dates (days) and weeks?

Edit: "weeks" should be the index of the week in a date range, not a year. I apologize for the ambiguity.

+8
date r
source share
3 answers

Do you only need the number of completed 7-day intervals from the first record?

dvec <- as.Date("2001-04-01")+0:90 dweek <- as.numeric(dvec-dvec[1]) %/% 7 dweek[1:21] # [1] 0 0 0 0 0 0 0 1 1 1 1 1 1 1 2 2 2 2 2 2 2 
+16
source share

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.

+20
source share

strftime is your friend ...

 ? strftime # to see the help and the format set.seed(1) dates <- Sys.Date() + sample(1:365, size = 10) R> dates [1] "2012-02-11" "2012-03-21" "2012-06-01" "2012-09-30" [5] "2012-01-18" "2012-09-25" "2012-10-11" "2012-06-30" [9] "2012-06-18" "2011-11-28" # %j for julian day - number of the day since the 1st of january each year R> strftime(dates, format = "%j") # or format(dates, format = "%j") [1] "042" "081" "153" "274" "018" "269" "285" "182" "170" "332" R> strftime(dates, format = "%w") [1] "6" "3" "5" "0" "3" "2" "4" "6" "1" "1" # my locale is in French so... R> strftime(dates, format = "%A") [1] "samedi" "mercredi" "vendredi" "dimanche" "mercredi" [6] "mardi" "jeudi" "samedi" "lundi" "lundi" 

By the way, what do you mean by day, day for a month, week or year?

+8
source share

All Articles