[Solved] Manually performing linear regression in R [closed]


It’s not clear how strict you want to be with the no package requirement. If you are willing to use the stats package (which most people don’t really even think of as a package because it comes standard with base R and you don’t have to load it with library()), then you can just call the usual “linear model” function lm().

Using `lm()`

fit <- lm(y ~ x + z, data = your_data_frame)
summary(fit)

Using matrix algebra

In contrast, you can also take the more pretentious route of coding the matrix algebra to fit these parameters manually. This involves no packages, other than base R.

X <- as.matrix(your_data[, c('x', 'z')]) # extract your predictors
X <- cbind(1, X) # add an intercept to your design matrix
y <- your_data$y

betas <- solve(t(X) %*% X) %*% t(X) %*% y

EDIT: Note that these approaches assume no missing data (i.e., that every row has a y, x, and z value).

6

solved Manually performing linear regression in R [closed]