This function fits a Polynomial Regression to a dataset.

fit_polynomial_regression(data, x_vars, y_var, degree = 2)

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

degree

The degree of the polynomial (default = 2)

Value

A list containing the fitted coefficients and the design matrix

Examples

# Generate sample data
set.seed(123)
n <- 100
p <- 10
data <- data.frame(matrix(runif(n * p, -1, 1), n, p))
colnames(data) <- paste0("x", 1:p)
data$y <- data$x1^2 + data$x2^2 + rnorm(n, sd = 0.1)

# Fit the Polynomial Regression using the function
fit <- fit_polynomial_regression(data, x_vars=paste0("x", 1:p), y_var="y", degree=2)

# Print the fitted coefficients
print(fit$coefficients)
#>                     [,1]
#> (Intercept)  0.531698340
#> x1           0.013835713
#> x2           0.062894248
#> x3          -0.152015160
#> x4           0.018695884
#> x5          -0.053018658
#> x6           0.090755029
#> x7           0.117732084
#> x8           0.127326957
#> x9          -0.129683291
#> x10         -0.107814030
#> x1:x2       -0.438951501
#> x1:x3       -0.208277595
#> x1:x4        0.308013759
#> x1:x5       -0.182872795
#> x1:x6        0.021520145
#> x1:x7        0.045353052
#> x1:x8        0.168577838
#> x1:x9       -0.406249487
#> x1:x10       0.067611702
#> x2:x3       -0.414031031
#> x2:x4       -0.097433521
#> x2:x5        0.261131711
#> x2:x6       -0.122806553
#> x2:x7        0.320497930
#> x2:x8        0.411357678
#> x2:x9       -0.226041517
#> x2:x10      -0.125186653
#> x3:x4        0.112601087
#> x3:x5       -0.046251194
#> x3:x6        0.066297845
#> x3:x7        0.118504681
#> x3:x8        0.148042849
#> x3:x9        0.204129213
#> x3:x10       0.078128641
#> x4:x5        0.055471818
#> x4:x6        0.158668419
#> x4:x7       -0.069792244
#> x4:x8       -0.136195469
#> x4:x9        0.238636629
#> x4:x10      -0.114048213
#> x5:x6       -0.084359651
#> x5:x7        0.026269943
#> x5:x8       -0.086713237
#> x5:x9        0.095877469
#> x5:x10      -0.014433712
#> x6:x7        0.387915579
#> x6:x8       -0.177870242
#> x6:x9       -0.050609122
#> x6:x10      -0.333896158
#> x7:x8       -0.108318446
#> x7:x9       -0.068611498
#> x7:x10      -0.056023509
#> x8:x9        0.177514479
#> x8:x10      -0.009937898
#> x9:x10       0.100577211