Or put it differently: How can I keep my ts index? Most of the time I use a time series in a calculation it's not a ts object anymore. What strategy should I follow when writing functions to return a ts object and keep the index information?
E.g.:
#standard Hodrick Prescott Filter
hpfilter <- function(x,lambda=1600){
eye <- diag(length(x))
result <- solve(eye+lambda*crossprod(diff(eye,lag=1,d=2)),x)
### this is what I am talking about :)
### intuitively i´d maybe add something like this
result <- ts(result,start=start(x),end=end(x),frequency=frequency(x))
###
return(result)
}
However, I feel that this clumsy and cumbersome. Is there a more elegant way to do it (maybe I should into classes..)?
With the
coredata
function in thezoo
package you can access the data portion of ats
orzoo
object. I would change you code toand run
which yields
With time series, subsetting and quite some other functions cause conversion to a matrix or a vector. You don't have to rebuild the time series, you can just transfer the attributes of the original
ts
to the result.You can use subsetting also to change (but not to append) the values in the time series :