x <- c(16,20,24,28,32,36,40,44,48,52) y <- c(14,13,18,19,22,23,24,28,30,29) model <- lm(y~x) # linear model (linear regression, OLS) summary(model) plot(x,y,xlab="Income",ylab="Consumption") abline(model) # Comment-out # OLS via Linear Algebra y <- cbind(y) y X <- cbind(rep(1,10),x) # column combine #rep replicate # t transpose X # %*% matrix multiplication # solve matrix inverse bOLS <- (solve(t(X)%*%X)) %*% (t(X)%*%y) bOLS t(X)%*%X solve(t(X)%*%X) t(X)%*%y > t(X)%*%X x 10 340 x 340 12880 > solve(t(X)%*%X) x 0.97575758 -0.0257575758 x -0.02575758 0.0007575758 > t(X)%*%y y 220 x 8120 > bOLS y 5.5151515 x 0.4848485 # Example of a LOOP with iterations sumy <- 0 for(i in 1:length(y)){ sumy <- sumy + y[i] } sumy