# Calculate Mean Squared Residuals (MSR) in R

Mean Squared Residuals (MSR) is ratio between Sum Squared Residuals and the number of observations, i.e., n. The following is the formula of MSR.

$MSR=\frac{SSR}{n}=\frac{\sum_{i=1}^{n} (\hat{y_i}-y_i)^2 }{n}$

MSR can be used compare our estimated values and observed values for regression models. R can be used to calculate Mean Squared Residuals (MSR), and the following is the core syntax.

mean(residuals(fit)^2)

Below are 2 examples of how to calculate MSR for linear regression models in R.

## Example 1: Use data of mtcars

mtcarts is a built-in sample dataset in R. We can have a linear regression model of mpg as the DV and hp as the IV. We can use lm() to estimate the regression coefficients.

# use lm() to estimate regression coefficinets
fit <- lm(mpg~hp, data=mtcars)

# calculate Mean Squared Residuals (MSR)
mean(residuals(fit)^2)

Output:

[1] 13.98982

Thus, the Mean Squared Residuals (MSR) is 13.99.

## Example 2: Hypothetical data

x_1 = rep(c('City1','City2'),each=5)
x_2 = rep(c('store1','store2'), 5)
sales=c(10,20,20,50,30,10,5,4,12,4)

df <- data.frame (cities  = x_1,
stores = x_2,
sales=sales)

# use lm() to estimate regression coefficinets
fit <- lm(sales~x_1*x_2, data=df)

# calculate Mean Squared Residuals (MSR)
mean(residuals(fit)^2)

Output:

[1]69.85

Thus, the Mean Squared Residuals (MSR) is 69.85.