Search code examples
rrandom-forestforecasting

Is it possible to use the forecast function with a randomforest model in r?


Can I use the forecast function with randomforest? PFB my code for creating regression model with randomforest

Subsales<-read.csv('Sales.csv')
head(Subsales)

Sample DataSet

Date               SKU                            City   Sales
      <date>                               <chr>   <chr> <dbl>
1 2014-08-11 Vaseline Petroleum Jelly Pure 60 ml Jeddah1   378
2 2014-08-18 Vaseline Petroleum Jelly Pure 60 ml Jeddah1   348
3 2014-08-25 Vaseline Petroleum Jelly Pure 60 ml Jeddah1   314
4 2014-09-01 Vaseline Petroleum Jelly Pure 60 ml Jeddah1   324
5 2014-09-08 Vaseline Petroleum Jelly Pure 60 ml Jeddah1   352
6 2014-09-15 Vaseline Petroleum Jelly Pure 60 ml Jeddah1   453

Code

train_len=round(nrow(SubSales)*0.8) 
test_len=nrow(SubSales)

######Splitting dataset into training and testing#####

#### Training Set
training<-slice(SubSales,1:train_len) 
#### Testing Set
testing<-slice(SubSales,train_len+1:test_len)

training=training[c(1,4)]
testing=testing[c(1,4)]

library(randomForest)
set.seed(1234)
regressor = randomForest(formula=Sales~.,
                data=training,
                ntree=100)
y_pred = predict(regressor,newdata = testing)

Can I use forecast function instead of predict?


Solution

  • Since you ask a pretty broad question, I'll give you a broad answer. You'll have to start by training the random forest model. The function to then make predictions with the trained model is predict