[R-sig-Geo] How to get the number of week with "zoo"

Gabor Grothendieck ggrothendieck at gmail.com
Fri Dec 2 12:49:27 CET 2011


On Fri, Dec 2, 2011 at 6:23 AM, CRISTINA ARJONA <cristhine.arj at gmail.com> wrote:
> Dear list,
>
> I have an object of class zoo and use time() to extract the times:
>> class(Equiwz2010)
> [1] "zoo"
>> a = time(Equiwz2010)
>
>
> How could I convert the elements of a to the week of the year
> as integers (between 1 and 52)?
>
> I've tried extracting the month and the day,
>> as.vector(days(a[30]))
> [1] "12"
>> as.vector(months(a[30]))
> [1] "diciembre"
>
> but cannot find the way of getting the month as an integer
> (i.e., 12 for the example above).
>

1. There are more than 52 weeks in a year since 7 * 52 = 364 whereas a
year has 365 or 366 days so the 1-52 part of your question is not
possible without doing things like redefining a week or dropping one
or two days in each  year.  Assuming we don't do that there are still
many ways to define week number and it can depend on what time class
you are using for the index of your zoo object but this will provide
the definition of week number given in ?strptime with Date class dates
and for certain other classes:

# create some test data: Jan1, Feb1, ..., Dec1
library(zoo)
z <- zoo(1:12, seq(as.Date("2011-01-01"), length = 12, by = "month"))

# calculate week numbers which start at 0
as.numeric(format(time(z), "%W"))

If you are willing to redefine the last week of the year as having
more than 7 days then you can force it into 1-52 as shown here:

http://r.789695.n4.nabble.com/Missing-data-td4097332.html


2. The other percent codes on the ?strptime page can get you other
components of the date, e.g. as.numeric(format(dd, "%m")) for month
number (1-12)  You can also use the components of as.POSIXlt, e.g.

> str(unclass(as.POSIXlt(time(z))))
List of 9
 $ sec  : num [1:12] 0 0 0 0 0 0 0 0 0 0 ...
 $ min  : int [1:12] 0 0 0 0 0 0 0 0 0 0 ...
 $ hour : int [1:12] 0 0 0 0 0 0 0 0 0 0 ...
 $ mday : int [1:12] 1 1 1 1 1 1 1 1 1 1 ...
 $ mon  : int [1:12] 0 1 2 3 4 5 6 7 8 9 ...
 $ year : int [1:12] 111 111 111 111 111 111 111 111 111 111 ...
 $ wday : int [1:12] 6 2 2 5 0 3 5 1 4 6 ...
 $ yday : int [1:12] 0 31 59 90 120 151 181 212 243 273 ...
 $ isdst: int [1:12] 0 0 0 0 0 0 0 0 0 0 ...
 - attr(*, "tzone")= chr "UTC"

> as.POSIXlt(time(z))$mon + 1
 [1]  1  2  3  4  5  6  7  8  9 10 11 12

See ?as.POSIXlt

Also read the article on dates and times in R News 4/1 and also look
at its references.

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-sig-Geo mailing list