Load the GAM package

library(gam)

Create the data and visualize

mydata <- data.frame(x = seq(from = -1,
                             to = 1,
                             length.out = 200),
                     y = x^2 + 0.1*rnorm(n = length(x)))
plot(mydata$x, mydata$y)

Perform the GAM fit and plot results

mygam <- gam(y ~ s(x), data = mydata)
summary(mygam)

Call: gam(formula = y ~ s(x), data = mydata)
Deviance Residuals:
      Min        1Q    Median        3Q       Max 
-0.242329 -0.058734  0.004164  0.053196  0.382372 

(Dispersion Parameter for gaussian family taken to be 0.0098)

    Null Deviance: 19.4055 on 199 degrees of freedom
Residual Deviance: 1.9133 on 195.0002 degrees of freedom
AIC: -350.3177 

Number of Local Scoring Iterations: 2 

Anova for Parametric Effects
           Df  Sum Sq  Mean Sq F value Pr(>F)
s(x)        1 0.00051 0.000507  0.0517 0.8204
Residuals 195 1.91335 0.009812               

Anova for Nonparametric Effects
            Npar Df Npar F     Pr(F)    
(Intercept)                             
s(x)              3 594.26 < 2.2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
plot(mygam, residuals = TRUE)

Check the \(R^2\) value to assess fit

(Rsquared <- 1-(mygam$deviance/mygam$null.deviance))
[1] 0.9014021
LS0tCnRpdGxlOiAiU2ltcGxlIGV4YW1wbGUgb2YgdXNpbmcgR0FNIGZvciBub25saW5lYXIgYXNzb2NpYXRpb24gc3R1ZGllcyIKb3V0cHV0OiBodG1sX25vdGVib29rCi0tLQoKIyBMb2FkIHRoZSBHQU0gcGFja2FnZQoKYGBge3J9CmxpYnJhcnkoZ2FtKQpgYGAKCiMgQ3JlYXRlIHRoZSBkYXRhIGFuZCB2aXN1YWxpemUKCmBgYHtyfQpteWRhdGEgPC0gZGF0YS5mcmFtZSh4ID0gc2VxKGZyb20gPSAtMSwKICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0byA9IDEsCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbGVuZ3RoLm91dCA9IDIwMCksCiAgICAgICAgICAgICAgICAgICAgIHkgPSB4XjIgKyAwLjEqcm5vcm0obiA9IGxlbmd0aCh4KSkpCnBsb3QobXlkYXRhJHgsIG15ZGF0YSR5KQpgYGAKCiMgUGVyZm9ybSB0aGUgR0FNIGZpdCBhbmQgcGxvdCByZXN1bHRzCgpgYGB7cn0KbXlnYW0gPC0gZ2FtKHkgfiBzKHgpLCBkYXRhID0gbXlkYXRhKQpzdW1tYXJ5KG15Z2FtKQpwbG90KG15Z2FtLCByZXNpZHVhbHMgPSBUUlVFKQpgYGAKCiMgQ2hlY2sgdGhlICRSXjIkIHZhbHVlIHRvIGFzc2VzcyBmaXQKCmBgYHtyfQooUnNxdWFyZWQgPC0gMS0obXlnYW0kZGV2aWFuY2UvbXlnYW0kbnVsbC5kZXZpYW5jZSkpCmBgYA==