predict_knn_regression.Rd
This function predicts the response variable using the KNN Regression model.
predict_knn_regression(data, x_vars, y_var, new_data, k = 5)
A data frame containing the predictor and response variables
A character vector of column names corresponding to the predictor variables
A character string of the column name corresponding to the response variable
A data frame containing the new predictor variable values
The number of nearest neighbors to consider (default = 5)
A vector of predicted response variable values
# Generate sample data
set.seed(123)
n <- 100
p <- 2
data <- data.frame(matrix(runif(n * p, -1, 1), n, p))
colnames(data) <- paste0("x", 1:p)
data$y <- data$x1 + data$x2 + rnorm(n, sd = 0.1)
# Generate new data
new_data <- data.frame(matrix(runif(10 * p, -1, 1), 10, p))
colnames(new_data) <- paste0("x", 1:p)
# Predict the response variable using the KNN model
predictions <- predict_knn_regression(data, x_vars=paste0("x", 1:p), y_var="y", new_data, k=5)
print(predictions)
#> [1] 0.63159072 -0.01214449 0.23325475 0.13740348 -0.67457685 -0.79484831
#> [7] 1.23088187 -1.21487426 -0.21936447 -0.58443805