Re: [R] How to get week of the year, scale 1-52?

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Tue, 18 Mar 2008 08:54:00 -0400

On Tue, Mar 18, 2008 at 7:55 AM, Lauri Nikkinen <lauri.nikkinen_at_iki.fi> wrote:
> R users,
>
> I have a vector of dates
>
> days <- seq(as.Date("2007/1/1"), as.Date("2008/1/31"), "days")
>
> and I would like to have week numbers from 1 to 52 for each year. How
> do I do that? Now I get 00-53 using
>
> format(days, "%W")
>
> > range(format(days, "%W"))
> [1] "00" "53"
>
> I have read "Date and Time Classes in R" (R news 01/04 by Gabor
> Grothendieck and Thomas Petzoldt) with no help.
>

There are more than 7 * 52 days in a year.

Try this which labels the first 7 days as 0, the next as 1, ..., up to 52:

> d <- seq(as.Date("2008-01-01"), as.Date("2008-12-31"), "day")
> (julian(d) - julian(as.Date(cut(d, "years")))) %/% 7
  [1] 0 0 0 0 0 0 0 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 5 6 6 6  6 6 6 6 7
 [51] 7 7 7 7 7 7 8 8 8 8 8 8 8 9 9 9 9 9 9 9 10 10 10 10 10 10 10 11 11 11 11 11 11 11 12 12 12 12 12 12 12 13 13 13 13 13 13 13 14 14
[101] 14 14 14 14 14 15 15 15 15 15 15 15 16 16 16 16 16 16 16 17 17 17 17 17 17 17 18 18 18 18 18 18 18 19 19 19 19 19 19 19 20 20 20 20 20 20 20 21 21 21
[151] 21 21 21 21 22 22 22 22 22 22 22 23 23 23 23 23 23 23 24 24 24 24 24 24 24 25 25 25 25 25 25 25 26 26 26 26 26 26 26 27 27 27 27 27 27 27 28 28 28 28
[201] 28 28 28 29 29 29 29 29 29 29 30 30 30 30 30 30 30 31 31 31 31 31 31 31 32 32 32 32 32 32 32 33 33 33 33 33 33 33 34 34 34 34 34 34 34 35 35 35 35 35
[251] 35 35 36 36 36 36 36 36 36 37 37 37 37 37 37 37 38 38 38 38 38 38 38 39 39 39 39 39 39 39 40 40 40 40 40 40 40 41 41 41 41 41 41 41 42 42 42 42 42 42
[301] 42 43 43 43 43 43 43 43 44 44 44 44 44 44 44 45 45 45 45 45 45 45 46 46 46 46 46 46 46 47 47 47 47 47 47 47 48 48 48 48 48 48 48 49 49 49 49 49 49 49
[351] 50 50 50 50 50 50 50 51 51 51 51 51 51 51 52 52 attr(,"origin")
[1] "1970-01-01"



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 18 Mar 2008 - 12:56:35 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 18 Mar 2008 - 13:30:22 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive