我一直在R中丢失我的时间指数 - 我该怎么办呢? [英] I lose my time index in R all the time – what can I do about it?

查看:123
本文介绍了我一直在R中丢失我的时间指数 - 我该怎么办呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或换句话说:我如何保留我的ts指数?
大多数时候我在计算中使用时间序列它不再是ts对象。在编写返回ts对象的函数并保留索引信息时,我应该遵循什么策略?

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?

例如:

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

推荐答案

随着时间序列,子集和相当一些其他功能导致转换为矩阵或向量。您不必重建时间序列,只需将原始 ts 的属性传输到结果。

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)
}

这篇关于我一直在R中丢失我的时间指数 - 我该怎么办呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆