I have problems with evaluation lasso model. I am trying to predict inflation and there are still error.
# packages
library(readxl)
library(tidyverse)
library(ggplot2)
library(dplyr)
library(forecast)
library(zoo)
library(glmnet)
library(Metrics)
Canada <- load("Canada_new.RData")
n <- nrow(data)
train_size <- floor(0.7 * n) # You can adjust the training size as needed
# Create training and test sets
train_data <- head(data, train_size)
test_data <- tail(data, n - train_size)
train_data <- na.omit(train_data)
test_data <- na.omit(test_data)
lasso_model_and_evaluate <- function(data, window_size, horizon) {
n <- nrow(data)
mse_values <- c()
mae_values <- c()
for (i in 1:(n - window_size - horizon + 1)) {
train_index <- i:(i + window_size - 1)
test_index <- (i + window_size):(i + window_size + horizon - 1)
train_data <- data[train_index, ]
test_data <- data[test_index, ]
x_train <- as.matrix(train_data[, -which(names(train_data) == "Inflation")])
y_train <- train_data$Inflation
x_test <- as.matrix(test_data[, -which(names(test_data) == "Inflation")])
y_test <- test_data$Inflation
lasso_fit <- glmnet(x_train, y_train, alpha = 1)
predicted_values <- predict(lasso_fit, s = 0.01, newx = x_test)
mse <- mse(y_test, predicted_values)
mae <- mae(y_test, predicted_values)
mse_values <- c(mse_values, mse)
mae_values <- c(mae_values, mae)
}
return(list(mse_values = mse_values, mae_values = mae_values))
}
# Preddefinovanie veľkosti rolujúceho okna
window_size <- 60
# Vykonanie a vyhodnotenie LASSO modelu pre každý horizont
horizons <- c(1, 2, 3, 4)
results <- list()
for (horizon in horizons) {
result <- lasso_model_and_evaluate(data, window_size, horizon)
results[[paste("Horizon", horizon)]] <- result
}
# Print out the contents of the `results` list
print(results)
# Check the structure and contents of the results list
str(results)
# Accessing elements of the list
print(results[["Horizon1"]])
print(results[["Horizon2"]])
print(results[["Horizon3"]])
print(results[["Horizon4"]])
Error: $ operator is invalid for atomic vectors
Thank you in advance for any reply.