# Load necessary packages
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
library(ggplot2)
# Load data (replace "path/to/advertising.csv" with your actual file path)
f <- read.csv("C://Users//hp//Desktop//advertising.csv")
# View the structure and summary of the data
str(f)
## 'data.frame': 200 obs. of 4 variables:
## $ TV : num 230.1 44.5 17.2 151.5 180.8 ...
## $ Radio : num 37.8 39.3 45.9 41.3 10.8 48.9 32.8 19.6 2.1 2.6 ...
## $ Newspaper: num 69.2 45.1 69.3 58.5 58.4 75 23.5 11.6 1 21.2 ...
## $ Sales : num 22.1 10.4 12 16.5 17.9 7.2 11.8 13.2 4.8 15.6 ...
summary(f)
## TV Radio Newspaper Sales
## Min. : 0.70 Min. : 0.000 Min. : 0.30 Min. : 1.60
## 1st Qu.: 74.38 1st Qu.: 9.975 1st Qu.: 12.75 1st Qu.:11.00
## Median :149.75 Median :22.900 Median : 25.75 Median :16.00
## Mean :147.04 Mean :23.264 Mean : 30.55 Mean :15.13
## 3rd Qu.:218.82 3rd Qu.:36.525 3rd Qu.: 45.10 3rd Qu.:19.05
## Max. :296.40 Max. :49.600 Max. :114.00 Max. :27.00
# Fit the regression model
model <- lm(Sales ~ TV + Radio + Newspaper, data = f)
# Print the model summary
summary(model)
##
## Call:
## lm(formula = Sales ~ TV + Radio + Newspaper, data = f)
##
## Residuals:
## Min 1Q Median 3Q Max
## -7.3034 -0.8244 -0.0008 0.8976 3.7473
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.6251241 0.3075012 15.041 <2e-16 ***
## TV 0.0544458 0.0013752 39.592 <2e-16 ***
## Radio 0.1070012 0.0084896 12.604 <2e-16 ***
## Newspaper 0.0003357 0.0057881 0.058 0.954
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.662 on 196 degrees of freedom
## Multiple R-squared: 0.9026, Adjusted R-squared: 0.9011
## F-statistic: 605.4 on 3 and 196 DF, p-value: < 2.2e-16
##Assumptions
# Check linearity visually using scatterplots
plot(f$TV, model$residuals, main = "Residuals vs TV", xlab = "TV", ylab = "Residuals")
abline(h = 0, col = "red")

# Check normality of residuals using a Q-Q plot
qqnorm(model$residuals)
qqline(model$residuals, col = "red")

# Check homoscedasticity using residuals vs fitted values plot
plot(model$fitted.values, model$residuals, main = "Residuals vs Fitted Values", xlab = "Fitted Values", ylab = "Residuals")
abline(h = 0, col = "red")

# Function to calculate VIF
calculate_vif <- function(model) {
# Extract predictor variables
X <- model.matrix(model)
vif_values <- sapply(2:ncol(X), function(i) {
vif_i <- 1 / (1 - summary(lm(X[, i] ~ X[, -i]))$r.squared)
return(vif_i)
})
# Assign variable names to VIF values
names(vif_values) <- colnames(X)[-1]
return(vif_values)
}
# Calculate and print VIF values
vif_values <- calculate_vif(model)
print(vif_values)
## TV Radio Newspaper
## 1.004611 1.144952 1.145187