Thanks @ ran2. I worked on your proposal and managed to solve this problem, but in a rather difficult way. First of all, I could not get any "apply family" function to work correctly on the xts object, preserving its structure. The usual feed using (x, MARGIN = 2, ..) for column use showed promise, but settled on the coredata statement. lapply etc. gave distorted lists.
Then I went into the for loop. But since x <-na.omit (x) changes the length of the variable, it cannot replace the original loop.
> for(i in 1:ncol(USDATAq)) { + USDATAq[,i]<-hpfilter(USDATAq[,i]) + }
Error in NextMethod (.Generic): the number of elements to replace is not a multiple of the replacement length
So, I had to add obscene code to hpfilter to "merge the result back to the original (with NA) and then return the variable. This merge corresponds to two variables by date (hence length) filling NA into the result. Then this result can replace the original in the loop.In conclusion, I had to change hpfilter to:
hpfilter <- function(x,lambda=2){ y<-na.omit(x) eye <- diag(length(y)) coredata(y) <- solve(eye + lambda * crossprod(diff(eye, lag=1, d=2)), coredata(y)) xy<-merge(x,y) return(xy[,2]) }
and then use the loop above to finally get the results without errors. My knowledge of R is so rudimentary that there are probably simpler ways to do this. But at least I can continue. Thanks to everyone for pointing me in the right direction. I still welcome further corrections in my code above.
Tatha source share