I lose the time index in R all the time - what can I do?

Or in another way: how can I save the ts index? Most of the time I use time series in the calculation, this is not a ts object. What strategy should you follow when writing functions to return a ts object and store index information?

For instance:

#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 it is awkward and cumbersome. Is there a more elegant way to do this (maybe I should deal with classes?)?

+3
source share
2 answers

With time series, a subset and some other functions cause conversion to a matrix or vector. You do not need to restore time series, you can just transfer the attributes of the source ts to the result.

 hpfilter <- function(x,lambda=1600){ eye <- diag(length(x)) result <- solve(eye+lambda*crossprod(diff(eye,lag=1,d=2)),x) attributes(result) <- attributes(x) return(result) } 

You can also use a subset to change (but not add) values ​​in a time series:

 hpfilter <- function(x,lambda=1600){ eye <- diag(length(x)) x[] <- solve(eye+lambda*crossprod(diff(eye,lag=1,d=2)),x) return(x) } 
+8
source

Using the coredata function in the zoo package, you can access the data part of the ts or zoo object. I would change your code to

 library(zoo) #standard Hodrick Prescott Filter hpfilter <- function(x,lambda=1600){ eye <- diag(length(x)) coredata(x) <- solve(eye + lambda * crossprod(diff(eye, lag=1, d=2)), coredata(x)) return(x) } 

and run

 foo <- ts(rnorm(10), frequency = 4, start = c(1959, 2)) bar <- hpfilter(foo) 

what gives

 > foo Qtr1 Qtr2 Qtr3 Qtr4 1959 0.8939882 -1.8442215 -0.8959187 1960 -0.2658590 0.5855087 -0.7167737 -1.9318533 1961 0.3489802 -0.6300171 -0.6523006 > bar Qtr1 Qtr2 Qtr3 Qtr4 1959 -0.3589312 -0.3939791 -0.4282439 1960 -0.4618490 -0.4952099 -0.5286198 -0.5616964 1961 -0.5941750 -0.6266472 -0.6591151 
+5
source

All Articles