# ------------------------------------------------------------------
# File name: curve_fitting.R
#
# Linear Model function lm(y~x) computes the least square fit line to data points;
# y as a function of x. Type ?formula for help with legal formulas.
# lm() can also be used to fit nonlinear models where the parameters enter into model linearly.
#
# Version: 2.1
# Authors: H. Kocak, University of Miami and B. Koc, Stetson University
# References:
# https://www.r-project.org
# ------------------------------------------------------------------
# Fit a line to two data points; a good test of lm()
x2 = c(1, 2)
y2 = c(1.5, 2.5)
plot(x2, y2, main="Unique line through 2 points", xlim=c(0, 4), ylim = c(0, 4))
# Compute the least square line, save output in ls_fit_line
ls_fit_line = lm(y2 ~ x2)
print(ls_fit_line)
# Plot the least square line stored in ls_fit_line
abline(ls_fit_line, col="red")
# Print the vector containing intercept and slope the line
print(coef(ls_fit_line))
# Lots more info
print(summary(ls_fit_line))
par(ask=TRUE)
# Compute least-square line fit for 3 data points
x3 = c(1, 2, 3)
y3 = c(1.5, 2.5, 2.8)
plot(x3, y3, main="Best-fit line through 3 points", xlim=c(0, 4), ylim = c(0, 4))
fit3 = lm(y3 ~ x3)
abline(fit3, col = "red")
print(fit3)
# Lots more info about the fitness
print(summary(fit3))
# Compute the parabola through 3 data points
plot(x3, y3, main="Unique parabola through 3 points", xlim=c(0, 6), ylim = c(0, 6))
fit_parabola3 = lm(y3 ~ x3 + I(x3^2))
print(fit_parabola3 )
curve(coef(fit_parabola3)[1] + coef(fit_parabola3)[2]* x + coef(fit_parabola3)[3]*x^2,
0, 6, col = "red", add=TRUE)
# Compute a best-fit parabola for 4 data points
x4 = c(1, 2, 3, 4)
y4 = c(1.5, 2.5, 2.8, 1.7)
plot(x4, y4, main="Best-fit parabola through 4 points", xlim=c(0, 6), ylim = c(0, 6))
fit_parabola4 = lm(y4 ~ x4 + I(x4^2))
print(fit_parabola4)
curve(coef(fit_parabola4)[1] + coef(fit_parabola4)[2]* x + coef(fit_parabola4)[3]*x^2,
0, 6, col = "red", add=TRUE)
# Add the predicted points
points(x4, predict(fit_parabola4), col = "green")