I'm using the rpart library to try forecasting the electricity consumption from Australia (example from the book Introductory Time Series with R):

 CBE : 
choc    beer    elec
1451    96.3    1497
All the data is separate in months from 1958 til 1970

www <- "http://staff.elena.aut.ac.nz/Paul-Cowpertwait/ts/cbe.dat"
CBE <- read.table(www, header = T)
Elec.ts <- ts(CBE[, 3], start = 1958, freq = 12)


fit <- rpart(elec~elec, method="anova", data=CBE)
pre <- predict(fit)

Elec.predict <- ts(pre[], start = 1958, freq = 12)
plot(cbind(Elec.ts,Elec.predict ))

It's really simple, the R program does not run, if I try to create a model using the elec data it self.

Am I using it wrong?
How Can I use this library properly ?

  • 1
    $\begingroup$ Cross-posted: stackoverflow.com/questions/33622951/… $\endgroup$
    – user81847
    Commented Nov 10, 2015 at 4:45
  • $\begingroup$ @Pascal I'm trying to get some help. can you help me? $\endgroup$ Commented Nov 10, 2015 at 4:48
  • $\begingroup$ Elec is highlighted - is it some sort of a keyword in R? also - you use Elec to fetch the CBE data. why do you then plug the CBE data to the regression, not the Elec data? $\endgroup$
    – metjush
    Commented Nov 10, 2015 at 9:10
  • $\begingroup$ @metjush sorry I will make more clear. I will update $\endgroup$ Commented Nov 10, 2015 at 11:48

1 Answer 1


If you want an analog to the autoregressive models, you need to regress elec against lagged elec.

nLag <- 6 # regression in the 6 last lags 
CBE <- setDT(CBE)[, paste0('elec', 1:nLag) := shift(elec, 1:nLag)][] # making the lags as inputs 
fit <- rpart(elec~., method="anova", data=CBE)
  • $\begingroup$ Hey is that work ? Have you tried ? $\endgroup$ Commented Nov 10, 2015 at 11:55
  • $\begingroup$ This looks reasonable - give it a try Alvaro. I think the problem was the elec~elec part. It was in fact regressing the variable in time t on itself (also in time t). $\endgroup$
    – metjush
    Commented Nov 10, 2015 at 13:59

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.