以下是statweek
函數。主要參數可以是日期的字符向量(例如,在讀取data.frame之後的默認值)。您可以指定日期的格式(有一個默認:format="%d-%m-%Y"
)
d1 <- c("01-01-2013","06-01-2013","01-01-2006","08-01-2006") # format="%d-%m-%Y"
d2 <- c("01/01/2013","06/01/2013","01/01/2006","08/01/2006") # format="%d/%m/%Y"
statweek = function(dates, format="%d-%m-%Y", ...) {
# convert to Date
dates = as.Date(dates, format=format, ...)
# get correction for the first week of the year (0 if 1-Jan not a Sunday)
firstweek = 1 - as.numeric(format(as.Date(cut(dates, "year")), "%U"))
output = as.numeric(format(dates, "%U")) + firstweek
return(output)
}
而且例子:
statweek(d1)
[1] 1 2 1 2
statweek(d1, format="%d-%m-%Y")
[1] 1 2 1 2
statweek(d2, format="%d/%m/%Y")
[1] 1 2 1 2
歡迎來到SO。你應該給[一個可重複的例子](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – agstudy
請使用一個標題,可能有助於未來的搜索者好。你的代碼/答案如何對未來的搜索者有用?如果不能,那麼問題可能會縮小,並可能會被關閉。 –