This function predicts the response variable using the KNN Regression model.

predict_knn_regression(data, x_vars, y_var, new_data, k = 5)

Arguments

data

A data frame containing the predictor and response variables

x_vars

A character vector of column names corresponding to the predictor variables

y_var

A character string of the column name corresponding to the response variable

new_data

A data frame containing the new predictor variable values

k

The number of nearest neighbors to consider (default = 5)

Value

A vector of predicted response variable values

Examples

# 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