Lets see how linear equation can represented in the form of matrices.

Y = Bx + e

yhat = Bo + B1x

yhat = Bx [ where B = {bo abd B1}]

There are two ways to go about it.

Lets look at method one. Method one using centering of the data. By using this method the ouput obtained is only the slope, i.e B1

x_one <- mtcars$cyl # independent variable x
y_one <- mtcars$mpg # dependent variable y


# centering of data 
x1_one <- scale(x_one, center = TRUE, scale = FALSE) 
y1_one <- scale(y_one, center = TRUE, scale = FALSE)

# estimation of the slope
beta0 <- solve(t(x1_one)%*%x1_one)%*%t(x1_one)%*%y1_one

# estimation of intercept
beta1 <- mean(y_one) - beta0*mean(x_one)

print(beta1)
##          [,1]
## [1,] 37.88458

Lets now look at the second method. Method two uses design matrix. By using this method the output obtained is both an intercept and the slope of the linear equation.

# create a design matrix for independent variable x
x_two <- model.matrix(mtcars$mpg ~ mtcars$cyl) # you can add as many predictors 
y_two <- mtcars$mpg  # Dependent variable y


# Estimation of slope and intercept
betas <- solve(crossprod(x_two))%*%crossprod(x_two, y_two)

# Estimation of predicted values
yhat <- x_two%*%betas

# Estimation of error term
e <- y_two - yhat

colnames(betas) <- "Co-efficients" # change column names to "Co-efficients"

print(betas)
##             Co-efficients
## (Intercept)      37.88458
## mtcars$cyl       -2.87579