麻烦绑定ts对象 - 只允许替换元素?

时间:2010-10-03 10:57:10

标签: r

我想将arima模型的预测输出以熔融类型的数据格式转换为我原来的ts系列对象。但是我收到以下错误消息,我不明白:

Error in `[<-.ts`(`*tmp*`, ri, value = c(12.2567768232753, -0.0141881223732589,  : 
  only replacement of elements is allowed

这是一些可重现的代码,其中包含来自雅虎财经的一些示例数据:

# custom function to extract years from ts object
tsyears = function (ts){

years = as.data.frame(trunc(time(ts)))
return(years)

}

library(quantmod)
sp500 = new.env()

### get some fresh data directly from yahoo finance
getSymbols("^GSPC", env = sp500, src ="yahoo", from = as.Date("1960-01-01"),to =as.Date("2010-09-29") )


GSPC = sp500$GSPC

check what we got (last 6 entries)
tail(GSPC)

#calculate annual returns from all the adjusted closes
annual=annualReturn(GSPC)

model = arima(annual,c(1,1,0))
pd = predict(model,10)

q = ts(pd$pred,start=2010,end=2020)
w = as.ts(annual,start=1960,end=2009)

e=data.frame(tsyears(q),unclass(q),"prediction")
names(e) = c("years","return","series")

w = data.frame(tsyears(w),unclass(w),"historical")
names(w) = c("years","return","series")     

rbind(w,e)

我想要的是:

year   return   series
2008     5        original
2009     -3       original
2010     6        prediction
2011     4        prediction

等等。从那时起,我将融化数据集并将其与ggplot一起使用,为系列值指定不同的颜色。

1 个答案:

答案 0 :(得分:5)

您的tsyears函数返回包含ts对象的data.frame:

> str(tsyears(q))
'data.frame':   11 obs. of  1 variable:
 $ x: Time-Series  from 2010 to 2020: 2010 2011 2012 2013 2014 ...
> str(tsyears(w))
'data.frame':   50 obs. of  1 variable:
 $ x: Time-Series  from 1960 to 2009: 1960 1961 1962 1963 1964 ...

我认为您希望函数返回包含数字向量的data.frame。你不需要它来返回data.frame;只返回一个数字向量工作正常:

tsyears <- function(ts) as.numeric(trunc(time(ts)))