2011-12-14 141 views
0

我有一個包含兩個不同年份(2009和2010)的日期的數據集,並希望每個日期都有對應的星期編號。使用R計算每年基於日期的週數

我的數據集與此類似:

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 

我想有變量「周」與相應的星期數每個日期的第三列。

編輯: 注:一個星期1月1日開始,二星期1月8日開始,每年

任何幫助將高度讚賞。

巴茲

+0

這是你的作業嗎? – n0p 2011-12-14 20:02:11

+0

@nOp:根本沒有。我正在研究一組數據(10,000個動物),並需要計算我擁有的一組日期的相應週數。 – baz 2011-12-14 20:07:00

回答

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 
0

2011後回答

library(lubridate) 
mydf$week <- week(mydf$week) 

lubridate包是像這一天的日常任務簡單。