dates <- NULL
date <- as.Date(\"01/01/2014\",\"%d/%m/%Y\")
dates <- data.frame(date=as.Date(character())
,cal_day_in_year_num = numeri
You can make your own functions to do this in base. For example,
start.of.week <- function(date)
date - (setNames(c(6,0:5),0:6) [strftime(date,'%w')])
end.of.week <- function(date)
date + (setNames(c(0,6:1),0:6) [strftime(date,'%w')])
start.of.week(as.Date(c('2014-01-05','2014-10-02','2014-09-22','2014-09-27')))
# "2013-12-30" "2014-09-29" "2014-09-22" "2014-09-22"
end.of.week(as.Date(c('2014-01-05','2014-10-02','2014-09-22','2014-09-27')))
# "2014-01-05" "2014-10-05" "2014-09-28" "2014-09-28"
As Wave commented, you can just use +1 to change the date. You can also do the same as you have done without the need of the slow for
loop.
date <- as.Date("01/01/2014","%d/%m/%Y")
yday(date) <-yday(date) + 0:364
dates <- data.frame(date = date,
cal_day_in_year_num = yday(date),
cal_week_id = paste(year(date),sprintf("%02d",week(date)),sep=""),
cal_week_start_date = NA,
cal_week_end_date = NA
)
# find the minimum date in the time series
min_date <- min(dates$date)
# find the previous Monday of the minimum date
for(i in 1:7){
if(wday(min_date-i, label=TRUE)=="Mon"){
start_date <- min_date-i
}
}
# get the number of days between the minimum date and all days
diff_days <- as.numeric(difftime(dates$date,start_date, units="days"))
# Remove the excess days from each date
dates$cal_week_start_date <- dates$date-diff_days%%7
# Fix up the end of the week based on the start of the week
dates$cal_week_end_date <- dates$cal_week_start_date+7