For a data pair \((x_i,y_i)_{i=1}^n\), the ordinary least squares estimator will find the estimates of \(\hat\beta_0\) and \(\hat\beta_1\) that minimize the following function:
You can use the lm to fit a linear model and extract the estimated values and standard errors
Matrix Formulation
R is capable of conducting matrix operations with the following functions:
%*%: matrix multiplication
t(): transpose a matrix
solve(): computes the inverse matrix
Minimization Problem
Minimize the least squares using a numerical methods in R. The optim() function will minimize a function for set of parameters. We can minimize a function, least squares function, and supply initial values (0) for the parameters of interest.
Fit a Line using lm for the following data
x <-rpois(500, 6)y <--9* x +32+rnorm(500, sd =sqrt(2))lm_res <-lm(y ~ x) summary(lm_res)sqrt(vcov(lm_res))sigma(lm_res)^2
Fit a linear model using matrix operation
X <-cbind(rep(1, 500), x)solve(t(X)%*%X) %*%t(X) %*% y
Minimizing a function using optim
Find the value of x and y that will minimize the following function for any value a and b.
\[
f(x) = 2(x - 5)^2 + 11
\]
d <-function(x){2* (x -5) +11}optim(0, d)
Maximizing a function using optim
Find the value of x and y that will minimize the following function for any value a and b.
\[
f(x) = - 3 (x - 8)^2 + 9
\]
d <-function(x){2* (x -5) +11}optim(0, d)
Minimizing function using optim
Find the value of x and y that will minimize the following function for any value a and b.