Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble rbinding ts objects – only replacement of elements is allowed?

Tags:

r

I'd like to rbind the prediction output of an arima model to my original ts series object in a melt type of data format. But I get the following error message that I don't understand:

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

Here´s some reproducible code, with some example data from yahoo finance:

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

What I would like to have is:

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

and so forth. From then on I would melt the dataset and use it with ggplot assigning different colors to the series value.

like image 210
Matt Bannert Avatar asked Oct 03 '10 10:10

Matt Bannert


1 Answers

Your tsyears function returns a data.frame that contains a ts object:

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

I think you intended your function to return a data.frame containing a numeric vector. You don't need it to return a data.frame though; just returning a numeric vector works fine:

tsyears <- function(ts) as.numeric(trunc(time(ts)))
like image 108
Joshua Ulrich Avatar answered Sep 27 '22 16:09

Joshua Ulrich