I want to calculate the rolling forecast origin using the for loops that I have created.
Firstly, I created a for loop in order to create a random walk forecast of the independent variables and store them as a list. Now, I want to estimate rolling regression and then I want to forecast them and store those models as a list. After that, my intention was to create another loop in order to extract t+1 from every created model and calculate RMSE for every vector.
I have a problem with finishing the second for the loop and creating the third one in order to calculate RMSE values.
If anyone has any time, I would appreciate your help. Thank you.
Here is the code:
library(readxl)
library(tidyverse)
library(lubridate)
library(fpp2)
library(naniar)
zalihe_input <- read_excel("C:/Users/User/OneDrive/Radna površina/zalihe_input.xlsx")
zalihe_input <- zalihe_input %>%
mutate(pcy_ii = 100 * (ii - lag(ii,4))/ lag(ii,4)* 100)
View(zalihe_input)
#FORECASTING HORIZONT
H <- 8
#LAST POINT OF ESTIMATION
LP <- 72
#FORECAST UNTIL
FU <- zalihe_input %>%
nrow() - 1
#OUT-OF-SAMPLE FORECAST (FORECAST UNTIL), WHICH IS HERE 2021Q4 - 2017Q4
OF <- FU - LP - H
#CREATING DATAFRAME FOR ACTUAL VALUES
actual_values <- data.frame()
#SETTING THE FORECASTING DATE
actual_values <- subset(zalihe_input, vrijeme > "2017Q4" & vrijeme < "2022Q1", select = vrijeme)
#CREATING FOR LOOP FOR ROOLING OF ACTUAL VALUES
for (i in 1:H){
first <- LP + i
last <- first + H
actual_values[0 : H + i, i + 1] = zalihe_input$ii[first:last]
}
#FUNCTION FOR CALCULATING RMSE
rmse <- function(actual, pred) {
sqrt(mean( (actual - pred) ^ 2))
}
#CORRELATION
cor(zalihe_input$ii, zalihe_input$inv)
#CREATING FOR LOOP FOR ESTIMATIONS AND FORECASTS OF LIN.REG./ARIMA MODELS
list_df <- list()
model_rw_inv <- list()
model_rw_ex <- list()
model_rw_imp <- list()
model.rw <- list()
model.est <- list()
model.fore <- list()
for (i in 1:OF){
list_df[[i]] <- zalihe_input %>%
slice_head(n = (LP + i)) %>%
select(vrijeme, ii, inv, ex, imp, pcy_ii)
model_rw_inv[[i]] <- rwf(list_df[[i]][["inv"]], h = H, drift = TRUE)
model_rw_ex[[i]] <- rwf(list_df[[i]][["ex"]], h = H, drift = TRUE)
model_rw_imp[[i]] <- rwf(list_df[[i]][["imp"]], h = H, drift = TRUE)
#FORECASTING MODELS
# forecast(model_rw_inv, newdata = list_df[[i]], h = H)$mean
# forecast(model_rw_ex, newdata = list_df[[i]], h = H)
# forecast(model_rw_imp, newdata = list_df[[i]], h = H)
}
#ESTIMATION OD MODELS
for (i in 1:OF){
list_df[[i]] <- zalihe_input %>%
slice_head(n = (LP + i - 1))
#USING RW VALUES TO ESTIMATE AND FORECAST OUT-OF-SAMPLE ONE STEP AHEAD
model.est[[i]] <- lm(ii ~ inv + ex + imp, data = list_df[[i]])
model_fore[[i]] <- forecast(model_est[[i]], newdata = list_df[[i]], h = H)
}
#FOR LOOP FOR CALCULATING RMSE WITH T+1 FROM EVERY MODEL FORECAST
for (i in 1:H){
horizont_fore[[i]] <- model_fore[[i]][72 + i]
for (j in 1:H){
}
}
I am trying to run a forecasting function hw() in R with below parameters:
hw(TS, initial = 'simple', alpha = a,beta= b ,gamma=g,h=future_num)
where alpha, beta, and gamma vary from 0 to 1 with an increment of 0.1.
I want to run this function for all the combination of alpha, beta, and gamma on one go and so have written below code:
volume = 'UpdatedVol1'
TS <- ts(Data_summary[volume],start = c(sy,sm),frequency = freq)
model_out = data.frame()
for(i in 1:length(alpha)){
for(j in 1:length(beta)){
for(k in 1:length(gama)){
### Model Output ###
#alpha = 0.2
fore_hw <- hw(TS, initial = 'simple', alpha =
alpha[i],beta=beta[j],gamma=gama[k],h=future_num)
hw <- data.frame(ForecastVol =as.numeric(round(fore_hw$mean)))
hw$ModelName <- "Ex HW"
hw$Alpha <- alpha[i]
hw$Beta <- beta[j]
hw$Gama <- gama[k]
model_out <- rbind(model_out,hw)
}
}
}
where Data_summary is data frame with 150 rows, freq = 7 and future_num = 300
Is there any possibility to run the hw() function with all alpha, beta, and gamma values at once? or any option to optimise this code as it is taking more than 8 mins to run this code
rbind() inside a loop is notoriously inefficient. See The Second Circle of R Hell in the R Inferno for a detailed explanation.
A quick fix is to put all the model results in a list and then use rbind once at the end:
# create a list and counter
results <- list()
counter <- 1
volume = 'UpdatedVol1'
TS <- ts(Data_summary[volume],start = c(sy,sm),frequency = freq)
model_out = data.frame() ## this seems to be unused??
for(i in 1:length(alpha)){
for(j in 1:length(beta)){
for(k in 1:length(gama)){
### Model Output ###
#alpha = 0.2
fore_hw <- hw(TS, initial = 'simple', alpha =
alpha[i],beta=beta[j],gamma=gama[k],h=future_num)
hw <- data.frame(ForecastVol =as.numeric(round(fore_hw$mean)))
hw$ModelName <- "Ex HW"
hw$Alpha <- alpha[i]
hw$Beta <- beta[j]
hw$Gama <- gama[k]
# add to the list and increment the counter
results[[counter]] <- hw
counter <- counter + 1
}
}
}
results <- do.call(rbind, results) # one rbind at the end
# (you can use `dplyr::bind_rows` or `data.table::rbindlist` to do this faster)
You could certainly do better than this too, but this will be a vast improvement with minimal changes.
So I'm trying to process the data ("final_ts") in order to make a forecast for the time series using kernel functions and doing parallel computing. The analysis is made this way: 1) analyse the empirical time series, 2) run a standard variable
selection to subset only those variables and their time-lags that provide the best validation error. 3) Run the same analysis described above to choose the optimal regularization parameters and kernel function of the regularized algorithm. As a result I show the RMSE (root mean squared error).
The code is not mine, and I'm trying to set it without problems, but as I do not have so much experience, I can't understand how to solve (I've spent 2 days trying to find the solution so if you help me I would be so grateful) the problem which occured: "The object '....' not found".
So the MAIN CODE looks like this (I'll try to make explanation on what happens, please don't judge me):
#download the libraries:
rm(list=ls(all=TRUE))
suppressMessages(library(Matrix))
suppressMessages(library(quantreg))
suppressMessages(library(parallel))
suppressMessages(library(compiler))
suppressMessages(library(lars))
suppressMessages(library(elasticnet))
suppressMessages(library(caret))
options(warn=-1)
#####################################################################################
#Download the sources (I'll show them in the end as a code)
###########Take the file###
ShowPlot = FALSE
lags = TRUE
ModelName = 'final_ts'
FileName = paste(ModelName, '.txt', sep = '')
########Calculate the logspace and the standard error functions #################
logspace <- function(d1, d2, n) exp(log(10)*seq(d1, d2, length.out=n))
std_err <- function(x) sd(x)/sqrt(length(x))
############# Choose the kernel function: we have 4 of them, but we try the second one #####
Kernel.Options = c('Exponential.Kernel', 'Epanechnikov.Kernel', 'TriCubic.Kernel', 'Matern.Kernel')
Regression.Kernel = Kernel.Options[1]
############# Choose the parameters for cross validation ####
lambda = logspace(-3,0,15)
if(Regression.Kernel == 'Exponential.Kernel'){
tht = seq(from = 0., to = 10, length = 30)
}else{
tht = seq(from = 0.1, to = 3, length = 20)
}
parameters_on_grid = expand.grid(tht, lambda)
### Read Time series
d = as.matrix(read.table(FileName, header= T))
######################
original.Embedding = c('Pro', 'Syn','Piceu')
original.TargetList = original.Embedding
d = d[, original.Embedding]
#### Here you take combinations of lags (best lag are 1 - 2) #####
x.lag = 1; y.lag = 2; z.lag = 1
sp.lag.selection = c(x.lag, y.lag, z.lag)
lagged.time.series = make.lagged.ts(d, sp.lag.selection)
d = lagged.time.series$time.series
original.col = lagged.time.series$original.variables
if(lags == TRUE){ var.sel = original.col; }else{ var.sel = colnames(d)}
##### Names and embedding in the laged dataset
if(lags == TRUE){ colnames(d) = Embedding = TargetList = LETTERS[1:ncol(d)]}else{
Embedding = TargetList = original.Embedding
}
##### length of training and test set (2 points for testing, 28 - for training)
length.testing = 2
length.training = nrow(d) - length.testing
#### Preserve training for the interactions
ts.train.preserved = d[1:length.training, var.sel]
std.ts.train = Standardizza(ts.train.preserved)
#### Preserve testing for the test (you want your algorithm to learn the real structure of the model)
ts.test.preserved = d[(length.training + 1):nrow(d), var.sel]
#### Training set:
d.training = Standardizza(d[1:length.training, ])
#### You now need to standardize the test set using mean and sd of the training set
d.testing = Standardizza.test(ts.test.preserved,ts.train.preserved)
############## Prepare for parallel computing
Lavoratori = detectCores() - 2
cl <- parallel::makeCluster(Lavoratori, setup_strategy = "sequential")
####
RegressionType = ELNET_fit_
alpha = 0.85
### should you compute all the variables or not?
BestModel = BestModelLOOCV(cl, d.training, TargetList, Embedding, parameters_on_grid, RegressionType,alpha)
I also found a fourmula for calculation of kernel function (it may be put in a SPECIAL r (SOURCE 1)):
Exponential.Kernel <- function(dst, theta){
dbar <- mean(dst)
krnl <- exp(-theta*dst/dbar)
return(krnl)
}
Exponential.Kernel <- cmpfun(Exponential.Kernel)
The formulas for finding the best leave-one-out cross-validation parameters is below (SOURCE 2):
########################### Cross Validation (Leave-one-out) ##################################
BestModelLOOCV <- function(cl, X, TargetList, Embedding, grid, RegressionType,alpha){
mine_output = Jacobian_(cl, X, TargetList, Embedding, grid, RegressionType,alpha)
theta_opt = mine_output$th
lambda_opt = mine_output$lm
mine_c0 = mine_output$c0
mine_output = mine_output$J
J_ = list()
C0_ = do.call(cbind, lapply(1:ncol(X), function(x, M) unlist(M[[x]]), mine_c0))
colnames(C0_) = sapply(TargetList,function(x) paste("c0_", x, sep = ""))
for(k in 1:(nrow(X) - 1)){
J_[[k]] = do.call(rbind, lapply(1:ncol(X), function(x, M, i) unlist(M[[x]][i,]), mine_output, k))
rownames(J_[[k]]) = Embedding
colnames(J_[[k]]) = Embedding
}
BestCoefficients = list()
BestCoefficients$J = J_
BestCoefficients$c0 = C0_
BestParameters = list()
BestParameters$BestTH = theta_opt
BestParameters$BestLM = lambda_opt
return(list(BestCoefficients = BestCoefficients, BestParameters = BestParameters))
}
#####Compute the jacobian
Jacobian_ <- function(cl, X, TargetList, Embedding, grid, RegressionType,alpha){
J = c0 = list()
th = lm = c()
n_ = 1
FUN = match.fun(RegressionType)
for(trg in TargetList){
RegularizedParameters <- LOOCrossValidation(cl, X, trg, Embedding, grid, RegressionType,alpha)
########## Now compute the optimum regularized coefficients
J[[n_]] = FUN(X, trg, Embedding, RegularizedParameters$BestTH, RegularizedParameters$BestLM,alpha)
th = c(th, RegularizedParameters$BestTH)
lm = c(lm, RegularizedParameters$BestLM)
c0[[n_]] = J[[n_]]$c0
J[[n_]] = J[[n_]][-1]
n_ = n_ + 1
}
return(list(J = J, c0 = c0, th = th, lm = lm))
}
In order to compute the elastic-net regularization function you may use this formula (SOURCE 3):
ELNET_fit_ <- function(time.series, targ_col, Embedding, theta, lambda,alp){
Edim <- length(Embedding)
coeff_names <- sapply(colnames(time.series),function(x) paste("d", targ_col, "d", x, sep = ""))
block <- cbind(time.series[2:dim(time.series)[1],targ_col],time.series[1:(dim(time.series)[1]-1),])
block <- as.data.frame(apply(block, 2, function(x) (x-mean(x))/sd(x)))
lib <- 1:dim(block)[1]
pred <- 1:dim(block)[1]
coeff <- array(0,dim=c(length(pred),Edim + 1))
colnames(coeff) <- c('c0', coeff_names)
coeff <- as.data.frame(coeff)
for (ipred in 1:length(pred)){
libs = lib[-pred[ipred]]
q <- matrix(as.numeric(block[pred[ipred],2:dim(block)[2]]),
ncol=Edim, nrow=length(libs), byrow = T)
distances <- sqrt(rowSums((block[libs,2:dim(block)[2]] - q)^2))
### Kernel
Krnl = match.fun(Regression.Kernel)
Ws = Krnl(distances, theta)
############ Fit function
x = as.matrix(block[libs,2:dim(block)[2]])
y = as.matrix(block[libs,1])
x = x[seq_along(y), ]
y = y[seq_along(y)]
Ws = Ws[seq_along(y)]
x = Ws * cbind(1, x)
y = Ws * y
fit <- enet(x, y, lambda = lambda, normalize = TRUE, intercept = FALSE)
coeff[ipred,] <- predict(fit, s = alp, type="coefficients", mode="fraction")$coefficients
}
return(coeff)
}
ELNET_fit_ <- cmpfun(ELNET_fit_)
The auxiliary formulas for computation are as follows (SOURCE 4):
TakeLag <- function(X, species.to.lag, num.lag){
tmp = matrix(0, nrow(X), num.lag)
tmp[,1] = X[,species.to.lag]
tmp[1, 1] = NA
tmp[2:nrow(X), 1] = X[1:(nrow(X) - 1), species.to.lag]
if(num.lag > 1){
for(lag. in 2:num.lag){
tmp[,lag.] = X[,species.to.lag]
tmp[1, lag.] = NA
tmp[2:nrow(X), lag.] = tmp[1:(nrow(tmp) - 1), lag.-1]
}
}
tmp
}
make.lagged.ts <- function(X,sp.lag.selection ){
### X = time series
### sp.lag is a vector whose entry are the lags of each variable
### e.g., sp.lag = c(x.lag, y.lag, ..., u.lag)
s = list()
for(i in 1:length(sp.lag.selection)){
Lag.sp = TakeLag(X, original.Embedding[i], sp.lag.selection[i])
s[[i]] = cbind(X[,original.Embedding[i]], Lag.sp)
}
X = do.call(cbind,s)
### Remove the NA
X = X[-c(1:max(sp.lag.selection)),]
### Save the position of the unlagged variables
original.col = c()
for(k in 1:length(sp.lag.selection)){
if(k == 1){ original.col = c(original.col, 1)}else{
num.lags = sum(unlist(lapply(1:(k-1), function(x,X) X[x], sp.lag.selection)))
original.col = c(original.col, k + num.lags )
}
}
return(list(time.series = X, original.variables = original.col))
}
take.coeff <- function(X, col.to.extract, original.emb){
### To use when prediction are made using lagged variables
### Take as input the sequence X of Jacobian along the attractor
### and the species to look at
### return a new sequence of Jacobian of the interaction among those species
m = lapply(1:length(X$J), function(t, M, specie) M$J[[t]][specie,specie],
X, col.to.extract)
for(i in 1:length(m)){
colnames(m[[i]]) = rownames(m[[i]]) =original.emb
}
return(m)
}
Standardizza <- function(X){
### This return y = (x-meanx)/stdx
for(i in 1:ncol(X)){
X[,i] = (X[,i]- mean(X[,i]))/sd(X[,i])
}
return(X)
}
Standardizza.test <- function(X, Y){
### X = test set
### Y = training set
### This return y = (x-meanY)/stdY
for(i in 1:ncol(X)){
X[,i] = (X[,i]- mean(Y[,i]))/sd(Y[,i])
}
return(X)
}
###########################
#### Here you compute the quality of the forecast as mean correlation coefficient
The problem in the main code sounds like: object 'Regression.Kernel' not found, but I see it in the code, it's written. Maybe the problem is connected with the type of it? But if I take away the quotes in order to make it a "closure", I cannot impose the function restrictions.
Please, help me if you can as I don't know how to solve.
The original dataset ("final_ts.txt"):
decy Temp CTD_S OxFix Pro Syn Piceu Naneu
2011.74221 27.60333 36.20700 27.26667 58638.33333 13107.00000 799.66667 117.66667
2011.74401 26.97950 36.13400 27.05000 71392.50000 13228.50000 1149.00000 116.50000
2011.74617 24.99750 35.34450 24.80000 264292.00000 27514.00000 2434.50000 132.50000
2011.74692 24.78400 35.25800 25.82500 208996.50000 39284.00000 3761.75000 220.75000
2011.74774 27.34225 35.86800 27.82500 114617.25000 23115.00000 2337.00000 139.75000
2011.74950 26.47875 36.18175 27.20000 97008.00000 9775.75000 855.50000 77.50000
2011.75583 26.86500 36.14575 27.47500 76255.00000 10226.75000 783.00000 99.50000
2011.75654 27.04550 36.04950 27.60000 95017.75000 10546.25000 915.25000 77.75000
2011.75962 27.06567 36.46367 26.56667 75750.00000 10194.33333 687.00000 44.00000
2011.76101 27.44700 36.48150 27.90000 38556.50000 8204.75000 791.25000 118.75000
2011.76169 27.32325 36.50075 27.80000 29848.50000 8995.50000 727.00000 159.25000
2011.76245 26.87050 36.57350 26.40000 36323.50000 10897.00000 792.00000 87.50000
2011.76349 27.43900 36.89325 27.90000 17308.50000 9678.50000 559.00000 149.00000
2011.77171 26.74050 36.90550 26.10000 20976.50000 7516.00000 489.50000 41.50000
2011.77224 26.53500 36.77500 27.22500 27229.00000 7578.00000 606.75000 159.50000
2011.77288 26.65450 36.78500 27.32500 37897.50000 10493.50000 1008.75000 209.50000
2011.77444 27.24150 36.73800 26.80000 15551.00000 8159.50000 479.00000 70.50000
2011.77505 26.67560 36.74240 27.30000 27887.80000 5290.80000 510.00000 101.20000
2011.77568 27.65125 36.69225 28.10000 12850.00000 9944.75000 640.75000 120.00000
2011.77693 28.11500 36.32750 27.85000 5694.00000 10288.50000 507.00000 32.00000
2011.77751 28.61950 36.26325 28.72500 20486.75000 10465.00000 430.50000 82.75000
2011.77814 28.60425 36.23100 28.70000 27974.50000 6977.25000 554.00000 80.50000
2011.77968 28.47200 35.69000 28.40000 126778.00000 2840.00000 537.00000 27.00000
2011.78087 28.89400 35.60650 28.35000 49250.00000 5533.00000 1004.00000 5.50000
2011.78190 28.74100 35.46200 28.80000 35698.00000 1298.00000 308.00000 23.00000
2011.78713 28.80500 35.50100 28.70000 99450.00000 5410.00000 637.50000 50.50000
2011.78887 28.39250 35.90900 28.25000 116562.00000 3758.50000 582.50000 60.00000
2011.79078 28.10550 36.40150 28.20000 13403.00000 11285.00000 472.00000 73.50000
2011.79261 27.25650 36.78350 27.45000 11205.00000 10576.00000 630.00000 74.00000
Please, help if you have any guess as I don't have an idea what has gone wrong.
following is the code i am trying to run.The main objective is to run the model for different K values then after calculate the accuracies in order to choose the best K value.
so i thought of using for loop where every model.Result and the respective accuracy is stored in lists.,then after is sent out with respective k values..
but the thing is for the following code...the list isnt having any values from 1:29 and there is predicted values for 30..
k = 1:30
for(l in k){
pre[[l]] = knn(train_dataset,test_dataset,cl = labels_train, k = l)
}
output :
enter image description here
can someone help me out with this....like why the list is coming like that and what should be done in order to get the correct result..and why so..?
Here is a solution, with the models fit using the code in tacoman's comment.
library(class)
set.seed(1) # Make the results reproducible
knn_list <- lapply(1:30, function(l){
knn(train_dataset, test_dataset, cl = labels_train, k = l)
})
ok <- sapply(knn_list, '==', labels_test)
acc <- colMeans(ok)
which(acc == max(acc))
plot(acc, type = "b")
The for loop in the question can also be run, as long as the results list is created beforehand. The results are identical.
set.seed(1) # Make the results reproducible
k <- 1:30
pre <- vector("list", length = 30)
for(l in k){
pre[[l]] <- knn(train_dataset, test_dataset, cl = labels_train, k = l)
}
identical(pre, knn_list)
#[1] TRUE
Example data
set.seed(2021)
n <- nrow(iris)
i <- sample(n, 0.7*n)
train_dataset <- iris[i, -5]
test_dataset <- iris[-i, -5]
labels_train <- iris[i, 5]
labels_test <- iris[-i, 5]
I have dataset (HEART). I split it into chunks. I would like to predict each chunk with his (M=3) previous models. In this case, I would like to predict chunk number 10 - with models 7,8,9. chunk 9 - with models 6,7,8... chunk 4 - with models 1,2,3.
Here is my code:
library(caret)
dat1 <- read.csv(url("http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/processed.cleveland.data"), header = FALSE,sep = ",")
colnames(dat1) <- c(LETTERS[1:(ncol (dat1)-1)],"CLA")
dat1$CLA<-as.factor (dat1$CLA)
chunk <- 30
n <- nrow(dat1)
r <- rep(1:floor(n/chunk),each=chunk)[1:n]
d <- split(dat1,r)
N<-floor(n/chunk)
cart.models <- list()
for(i in 1:N){cart.models[[i]]<-rpart(CLA~ ., data = d[[i]]) }
for (i in (1+M):N) { k=0
for (j in (i-M):(i-1)) {
k=k+1
d[[i]][,(ncol(d[[i]])+k)]<-(predict(cart.models[[j]], d[[i]][,c(-14)], type = "class") )
}
}
I get the following Error:
Error in `[<-.data.frame`(`*tmp*`, , (ncol(d[[i]]) + k), value = c(1L, :
new columns would leave holes after existing columns
Your question is a bit puzzling, you load caret without using any functions from it. The objective seems like a time series analyses but instead of building on one chunk and predicting on the one that comes after it, you have a more complex desire, so createTimeSlices from caret won't do the trick.
You could create custom folds in caret with index and indexOut arguments in trainControl but that would ultimately lead to the creation of more models (21 to be exact) than is required for the presented objective (9). So I do believe loops are an appropriate way:
create the models:
library(rpart)
N <- 9
cart.models <- list()
for(i in 1:N){
cart.models[[i]] <- rpart(CLA~ ., data = d[[i]])
}
N can be 9 since 10 will not be utilized later on.
create a matrix to store the values:
cart.predictions <- matrix(nrow = chunk, ncol = length(4:10)*3)
it should have the same number of rows as there are predictions in each chunk (so 30) and it should have as many columns are there are predictions (three models for 4:10 chunks).
k <- 0 #as a counter
for (j in 4:10) { #prediction on chunks 4:10
p <- j-3
pred <- list()
for(i in p : (p+2)) { #using models (chink - 3) : (chunk - 1)
k = k + 1
predi <- predict(cart.models[[i]], d[[j]], type = "class")
cart.predictions[,k] <- predi
}
}
this creates a numeric matrix for predictions. By default when R converts factors to numeric it gives them numbers: 1 to the first level, 2 to the second etc - so to get the levels (0:4) you can just:
cart.predictions <- as.data.frame(cart.predictions - 1)
to create the column names:
names <- expand.grid(3:1, 4:10)
names$Var1 <- with(names, Var2 - Var1)
colnames(cart.predictions) <- make.names(paste0(names$Var1,"_", names$Var2))
lets check if it correct:
prediction from model 5 on chunk 6 converted to numeric
as.numeric(as.character(predict(cart.models[[5]], d[[6]], type = "class")))
should be equal to
cart.predictions[["X5_6"]] #that's how the names were designed
all.equal(as.numeric(as.character(predict(cart.models[[5]], d[[6]], type = "class"))),
cart.predictions[["X5_6"]])
#output
TRUE
or you can create a character matrix in the first place:
cart.predictions <- matrix(data = NA_character_, nrow = chunk, ncol = length(4:10)*3)
k <- 0 #as a counter
for (j in 4:10) {
p <- j-3
pred <- list()
for(i in p : (p+2)) {
k = k + 1
predi <- predict(cart.models[[i]], d[[j]], type = "class")
cart.predictions[,k] <- predi
}
}
cart.predictions <- as.data.frame(cart.predictions)
This should be the preferred method if the classes are certain "names".