开发者

I lose my time index in R all the time – what can I do about it?

开发者 https://www.devze.com 2023-02-24 19:51 出处:网络
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

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 
re开发者_开发技巧sult <- 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 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)
}


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           
0

精彩评论

暂无评论...
验证码 换一张
取 消