In this example, we'll use the built-in mtcars dataset in R, which contains information on various car models, including their mileage (mpg), weight (wt), and horsepower (hp). We'll estimate a simple linear regression equation to predict mpg based on wt and hp.
The Regression Equation
The general form of a multiple linear regression equation is:
Y = β0 + β1*X1 + β2*X2 + ε
where:
Y is the response variable (in our case, mpg)
X1 and X2 are predictor variables (in our case, wt and hp)
β0 is the intercept or constant term
β1 and β2 are coefficients for X1 and X2, respectively
ε is the error term
R Code
Here's the R code to estimate the regression equation:
r
# Load necessary libraries
library(ggplot2) # for plotting
library(broom) # for tidying model output
# Load the mtcars dataset (built-in R dataset)
data(mtcars)
# Explore the first few rows of the dataset
head(mtcars)
# Estimate the regression model: mpg ~ wt + hp
model <- lm(mpg ~ wt + hp, data = mtcars)
# Summarize the model
summary(model)
# Tidy the model output for easier reading
tidy_model <- tidy(model)
print(tidy_model)
# Use the model to make predictions
new_data <- data.frame(wt = 3.5, hp = 150)
predicted_mpg <- predict(model, new_data)
print(paste("Predicted MPG:", round(predicted_mpg, 2)))
# Visualize the relationship
ggplot(mtcars, aes(x = wt, y = mpg, color = hp)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
labs(title = "MPG vs. WT, colored by HP",
subtitle = "Linear Regression Fit",
x = "Weight (1000 lbs)",
y = "Miles Per Gallon",
color = "Horsepower") +
theme_minimal()
Explanation
Load Libraries: We load ggplot2 for data visualization and broom to tidy the model output, making it easier to read and work with.
Load Dataset: The mtcars dataset is loaded. You can replace this with your own dataset.
Explore Data: head(mtcars) shows the first few rows of the dataset to ensure it's loaded correctly.
Estimate Model: lm() function estimates the linear model. The formula mpg ~ wt + hp means we're predicting mpg using wt and hp.
Summarize Model: summary(model) provides detailed output, including coefficients, R-squared value, p-values, etc.
Tidy Model Output: tidy(model) from the broom package simplifies the model summary into a data frame format.
Make Predictions: We create a new_data data frame with specific wt and hp values and use predict() to estimate mpg for these inputs.
Visualization: A scatter plot with a linear regression line (geom_smooth(method = "lm")) visualizes the relationship between mpg and wt, colored by hp.
Interpreting the Output
The summary(model) will give you:
Coefficients: Estimate of β0 (Intercept), β1 (for wt), and β2 (for hp).
R-squared: Indicates the goodness of fit (higher is better, max = 1).
p-values: For each coefficient, indicates if the predictor is statistically significant (typically, p < 0.05 is considered significant).
Example output from summary(model) might look like: