I'm using the rpart
library from R to try forecasting the electricity consumption from Australia (example from the book Introductory Time Series with R):
library(rpart)
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)
plot(cbind(Elec.ts))
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 ?
Solving the problem with this script.
I have created a github site with all informations about the script and the time series data. http://alvarojoao.github.io/timeseriesExamples
library(caret)
library(ggplot2)
library(pls)
library(data.table)
library(rpart)
library(bst)
library(plyr)
nLag <- 12
khorizon <- 1
www <- "./databases/elec.dat"
CBE <- read.table(www, header = T)
base <- CBE
variable <- 'elec'
base$elec = (base$elec-min(base$elec))/(max(base$elec)-min(base$elec))
base <- setDT(base)[, paste0(variable, 1:nLag) := shift(elec, 1:nLag)][]
base <- base[(nLag+1):nrow(base),]
Elec.ts <- ts(CBE[, 1], start = 1958, freq = 12)
acf(CBE$elec)
plot(cbind(Elec.ts))
timeSlices <- createTimeSlices(1:nrow(base),
initialWindow =nrow(base)*2/3, horizon = khorizon , fixedWindow = FALSE)
str(timeSlices,max.level = 1)
trainSlices <- timeSlices[[1]]
testSlices <- timeSlices[[2]]
predTest <- c(1,2)
predTest <- predTest[0]
trueTest <- c(1,2)
trueTest <- trueTest[0]
for(i in 1:length(trainSlices)){
plsFitTime <- train(elec ~ .,
data = base[trainSlices[[i]],],
method = "treebag"
)
pred <- predict(plsFitTime,base[testSlices[[i]],])
true <- base$elec[testSlices[[i]]]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.