I have a really odd issue… I am using the to.weekly and to.period function to convert a daily xts object to weekly data. In most instances, I get the week-ending date as a Friday (day.of.week function will return 5) (e.g. "2010-01-08", "2011-02-11"), but there are a few cases where I get something other than Friday (Saturday/Sunday/Thursday/etc.)
I have tried to.weekly and to.period(x, period = 'weeks') and both return the same problem.
Why is this happening? Is there a work-around for this??
Thanks!!
[EDIT: EXAMPLE BELOW]
test.dates <- as.Date(c("2010-04-27","2010-04-28","2010-04-29","2010-04-30","2010-05-03","2010-05-04","2010-05-05","2010-05-06","2010-05-07","2010-05-10","2010-05-11","2010-05-12","2010-05-13","2010-05-14","2010-05-17","2010-05-18","2010-05-19","2010-05-20","2010-05-21","2010-05-22","2010-05-24","2010-05-25","2010-05-26","2010-05-27","2010-05-28","2010-06-01","2010-06-02","2010-06-03","2010-06-04"))
test.data <- rnorm(length(test.dates),mean=1,sd=2)
test.xts <- xts(x=test.data,order.by=test.dates)
#Function that takes in a vector of zoo/xts objects (e.g. "2010-01-08") and returns the day of the week for each
dayofweek <- function(x) {
placeholder <- vector("list",length=length(x))
names(placeholder) <- x
for(i in 1:length(x)) {placeholder[[i]] <- month.day.year(x[i])}
placeholder2 <- rep(NA,times=length(x))
for(i in 1:length(x)) {placeholder2[i] <- day.of.week(placeholder[[i]][[1]],placeholder[[i]][[2]],placeholder[[i]][[3]])}
return(placeholder2)}
This returns the date(s) that are not Friday: time(to.weekly(test.xts))[dayofweek(time(to.weekly(test.xts))) != 5]
You have 2 problems with your example:
dayofweekfunction is a bit cumbersome, and probably incorrect in its results.Here is a cleaned-up version of your code:
The only result of this function is
The problem of course, is that this week ends on
05-23-2010, but that date is not present in the time series. Therefore,to.weeklyuses the next closest date as the end point, which is05-22-2010. This is the source of your problem.Here is a better example, which reveals no issue with the
to.weeklyfunction.