2016-04-30 27 views
0

我將包含星期編號的列添加到包含日曆(天數列表)的數據框中。爲此使用strftime。它可以工作,但周計數從第0周開始。它應該從第1周開始,所以我試圖給週數列的每個元素加1。我收到錯誤消息「Calendar $ WkNumber中的錯誤+ 1:二進制運算符的非數字參數」。我怎麼能消除這個錯誤?謝謝!使用strftime創建星期編號(R)

#Make daily time sequence with Time & DayWk columns 
Calendar <- as.data.frame(seq(as.Date("2016/1/1"), as.Date("2016/1/20"), "days")) 
colnames(Calendar) <- "DateTime" 
Calendar$WkNumber <- strftime(Calendar$DateTime,format="%W") 
Calendar$WkNumber <- Calendar$WkNumber + 1 #=> this line produces error 

#Output for Calendar: 
    DateTime  WkNumber 
    1 2016-01-01  00 
    2 2016-01-02  00 
    3 2016-01-03  00 
    4 2016-01-04  01 
    5 2016-01-05  01 
    6 2016-01-06  01 
    7 2016-01-07  01 
    8 2016-01-08  01 
    9 2016-01-09  01 
    10 2016-01-10  01 
    11 2016-01-11  02 
    12 2016-01-12  02 
    13 2016-01-13  02 
    14 2016-01-14  02 
    15 2016-01-15  02 
    16 2016-01-16  02 
    17 2016-01-17  02 
    18 2016-01-18  03 
    19 2016-01-19  03 
    20 2016-01-20  03 

編輯:問題是100%可重複的。

+0

那行產生錯誤,因爲「WkNumber」是'character'類。轉換爲「數字」,它應該工作。即'as.numeric(Calendar $ WkNumber)+ 1' – akrun

+0

如果你看'str(Calendar)',你可以看到WkNumber是一個字符變量。 - >你需要先轉換爲數字。 – Heroka

+0

非常感謝。這解釋了。乾杯。 – Krug

回答

2

答案感謝搜到的意見:

Calendar$WkNumber <- as.numeric(strftime(Calendar$DateTime,format="%W"))+1