I am trying to do PCA on expanding window of data and use those principal components in expanding window regression to generate forecasts. Since I have to do this for multiple models, I have written a function for a simple PCA. Please see the code below
comp_fc <- function(data_input = NULL, dep_var = NULL, type = NULL){
pca_comp <- prcomp(data_input, center = TRUE, scale = TRUE)
sum_pca <- summary(pca_comp)
print(sum_pca$importance)
pca_comp <- zoo(pca_comp$x, rownames(pca_comp$x))
reg_exp <- roll_regres(dep_var ~ pca_comp[,1] + pca_comp[,2], width = 157, do_downdates = FALSE, do_compute = c("sigmas", "r.squareds", "1_step_forecasts"))
return(reg_exp$one_step_forecasts)
}
I would like to add expanding window method to calculate PCA. I tried to use for loop but when the loop reaches last point eventually all values will be replaced by the complete data set.
Any suggestions on how to proceed would be helpful. Thanks.