Frage

I'm trying to get the number of each particular week, i.e. 1 for the first week, 2 for the second, etc.

My data starts with Jan 1, 2012, and under the assumption that all dates/times are relevant to Chicago/CST6CDT timezone. Right off the bat I seem to be having a problem (with either my understanding or programming) getting the week function to give me what I need.

For example...

x=seq(as.POSIXlt("2012-1-1"), as.POSIXlt("2012-1-10"), by="day")
cbind(as.character(x), week(x))

...gives me...

      [,1]         [,2]
 [1,] "2012-01-01" "1" 
 [2,] "2012-01-02" "1" 
 [3,] "2012-01-03" "1" 
 [4,] "2012-01-04" "1" 
 [5,] "2012-01-05" "1" 
 [6,] "2012-01-06" "1" 
 [7,] "2012-01-07" "2" 
 [8,] "2012-01-08" "2" 
 [9,] "2012-01-09" "2" 
[10,] "2012-01-10" "2" 

January 7th, 2012, a Saturday, should be considered as part of the 1st week, right? Setting the timezone doesn't seem to help.

x=seq(as.POSIXlt("2012-1-1", tz="CST6CDT"), as.POSIXlt("2012-1-10", tz="CST6CDT"), by="day")

Is there a way around this?

War es hilfreich?

Lösung 2

This has to do with the way the function week is written in the package:

 > week()
 function (x) 
 yday(x)%/%7 + 1

In your case, for January 7, 2012:

 x = as.POSIXlt("2012-1-7")
 yday(x) = 1

Then:

 week(x) = (1%/%7) + 1 = 2

For it to work as you wish, try this:

 x=seq(as.POSIXlt("2012-1-1", tz = "UCT"), as.POSIXlt("2012-1-20", tz = "UTC"), by="day")
 cbind(as.character(x), (yday(x)-1)%/%7+1)

You get the following output:

#      [,1]         [,2]
# [1,] "2012-01-01" "1" 
# [2,] "2012-01-02" "1" 
# [3,] "2012-01-03" "1" 
# [4,] "2012-01-04" "1" 
# [5,] "2012-01-05" "1" 
# [6,] "2012-01-06" "1" 
# [7,] "2012-01-07" "1"   <<<
# [8,] "2012-01-08" "2" 
# [9,] "2012-01-09" "2" 
#[10,] "2012-01-10" "2" 
#[11,] "2012-01-11" "2" 
#[12,] "2012-01-12" "2" 
#[13,] "2012-01-13" "2" 
#[14,] "2012-01-14" "2" 
#[15,] "2012-01-15" "3" 
#[16,] "2012-01-16" "3" 
#[17,] "2012-01-17" "3" 
#[18,] "2012-01-18" "3" 
#[19,] "2012-01-19" "3" 
#[20,] "2012-01-20" "3" 

Andere Tipps

What you want is probably isoweek(), not week(). I have the same issues always with my calendar weeks :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top