[R] How to get week of the year, scale 1-52?
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Mar 18 13:54:00 CET 2008
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"
More information about the R-help
mailing list