根据使用R的日期计算每年的周数

时间:2011-12-14 20:01:26

标签: r date week-number

我有一个日期为2年不同年份(2009年和2010年)的数据集,并且希望每个日期都有相应的周数。

我的数据集与此类似:

  anim <- c(012,023,045,098,067)
  dob <- c("01-09-2009","12-09-2009","22-09-2009","10-10-2010","28-10-2010")
  mydf <- data.frame(anim,dob)
  mydf
    anim    dob
1   12   01-09-2009
2   23   12-09-2009
3   45   22-09-2009
4   98   10-10-2010
5   67   28-10-2010

我想在第三列中添加变量“week”,每个日期都有相应的周数。

编辑: 注意:第1周从1月1日开始,第2周从1月8日开始,每年

任何帮助都将受到高度赞赏。

巴兹

2 个答案:

答案 0 :(得分:3)

您对“一年中的一周”的定义

  

编辑:注意:第一周从1月1日开始,第二周从1月8日开始,每年

strftime支持的标准版本不同:

%U
    Week of the year as decimal number (00–53) using Sunday as the first day 1 
    of the week (and typically with the first Sunday of the year as day 1 of 
    week 1). The US convention.
%W
    Week of the year as decimal number (00–53) using Monday as the first day 
    of week (and typically with the first Monday of the year as day 1 of week 
    1). The UK convention.

所以你需要根据年日数来计算它。

mydf$week <- (as.numeric(strftime(as.POSIXct(mydf$dob, 
                                             format="%d-%m-%Y"), 
                                  format="%j")) %/% 7) + 1

答案 1 :(得分:0)

2011年后回答

library(lubridate)
mydf$week <- week(mydf$week)
对于像这样的日常任务,

lubridate套餐是直截了当的。