Lubridate周()给了我“错误”的一周,可能是TZ问题?

时间:2013-08-21 20:48:24

标签: r lubridate

我正在尝试获取每个特定周的数量,即第一周为1,第二周为2等。

我的数据从2012年1月1日开始,并假设所有日期/时间都与Chicago / CST6CDT时区相关。马上我似乎遇到了一个问题(无论是我的理解还是编程)让周功能给我我需要的东西。

例如......

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

...给我......

      [,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" 

2012年1月7日,一个星期六,应被视为第一周的一部分,对吗?设置时区似乎没有帮助。

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

有解决方法吗?

2 个答案:

答案 0 :(得分:2)

您想要的可能是isoweek(),而不是week()。我的日历周总是有同样的问题:)

答案 1 :(得分:1)

这与函数week写在包中的方式有​​关:

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

在您的情况下,2012年1月7日:

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

然后:

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

为了让它按您的意愿工作,请尝试以下

 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)

您将获得以下输出:

#      [,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"