3

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..)?

2 Answers 2

8

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.

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 use subsetting also to change (but not to append) the values in the 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)
}
1
  • 3
    1+ because attributes don't get used enough. Apr 15, 2011 at 10:24
5

With the coredata function in the zoo package you can access the data portion of a ts or zoo object. I would change you 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)

which yields

> 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           

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.