[R] extract week from date

Douglas Bates bates at stat.wisc.edu
Thu Apr 11 17:42:54 CEST 2002

```"Juan Ramon Gonzalez" <jrgonzalez at ico.scs.es> writes:

> Does anyone know how obtain the week of a date?
> (in SPPS the instruction is "xdate.week")

If you convert a date to a POSIXlt class, say by using the strptime
function, you get a list with components

`sec' 0-61: seconds

`min' 0-59: minutes

`hour' 0-23: hours

`mday' 1-31: day of the month

`mon' 0-11: months after the first of the year.

`year' Years since 1900.

`wday' 0-6 day of the week, starting on Sunday.

`yday' 0-365: day of the year.

`isdst' Daylight savings time flag. Positive if in force, zero if
not, negative if unknown.

You should be able to compute the week of the year from yday. I think
it would be ceiling(dd\$yday/7 + 0.5) but you should check this.

For example

> as.character(unique(cheese[,1]))
[1] "5/4/99"  "5/5/99"  "5/7/99"  "5/11/99" "5/12/99" "5/14/99" "5/18/99"
[8] "5/19/99" "5/21/99" "5/25/99" "5/27/99" "5/28/99" "8/3/99"  "8/4/99"
[15] "8/6/99"  "8/10/99" "8/11/99" "8/12/99" "8/13/99" "8/17/99" "8/18/99"
[22] "8/19/99" "8/20/99" "8/24/99" "8/25/99" "8/27/99" "8/31/99"
> dd <- strptime(as.character(unique(cheese[,1])), format = '%m/%d/%y')
> ceiling(dd\$yday/7)
[1] 18 18 18 19 19 19 20 20 20 21 21 21 31 31 31 32 32 32 32 33 33 33 33 34 34
[26] 34 35
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```