Author: Sulaiman Allouh
Date: 23/Oct/2024
{Exploratory Data Analysis} data(mtcars) head(mtcars) summary(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
mpg cyl disp hp drat wt qsec Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0 Min. :2.760 Min. :1.513 Min. :14.50 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5 1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 Median :19.20 Median :6.000 Median :196.3 Median :123.0 Median :3.695 Median :3.325 Median :17.71 Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7 Mean :3.597 Mean :3.217 Mean :17.85 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0 3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0 Max. :4.930 Max. :5.424 Max. :22.90 vs am gear carb Min. :0.0000 Min. :0.0000 Min. :3.000 Min. :1.000 1st Qu.:0.0000 1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000 Median :0.0000 Median :0.0000 Median :4.000 Median :2.000 Mean :0.4375 Mean :0.4062 Mean :3.688 Mean :2.812 3rd Qu.:1.0000 3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000 Max. :1.0000 Max. :1.0000 Max. :5.000 Max. :8.000
```{Visualize the data} library(ggplot2) ggplot(mtcars, aes(x = factor(am), y = mpg)) + geom_boxplot() + labs(x = “Transmission (0 = Automatic, 1 = Manual)”, y = “MPG”, title = “MPG by Transmission Type”)

```{Fit a simple linear model}
model1 <- lm(mpg ~ factor(am), data = mtcars)
summary(model1)
Residuals: Min 1Q Median 3Q Max -9.3923 -3.0923 -0.2974 3.2439 9.5077 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 17.147 1.125 15.247 1.13e-15 *** factor(am)1 7.245 1.764 4.106 0.000285 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 4.902 on 30 degrees of freedom Multiple R-squared: 0.3598, Adjusted R-squared: 0.3385 F-statistic: 16.86 on 1 and 30 DF, p-value: 0.000285
{Fit a simple linear model} model2 <- lm(mpg ~ factor(am) + wt + hp + qsec, data = mtcars) summary(model2)
Residuals: Min 1Q Median 3Q Max -3.4975 -1.5902 -0.1122 1.1795 4.5404 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 17.44019 9.31887 1.871 0.07215 . factor(am)1 2.92550 1.39715 2.094 0.04579 * wt -3.23810 0.88990 -3.639 0.00114 ** hp -0.01765 0.01415 -1.247 0.22309 qsec 0.81060 0.43887 1.847 0.07573 . --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 2.435 on 27 degrees of freedom Multiple R-squared: 0.8579, Adjusted R-squared: 0.8368 F-statistic: 40.74 on 4 and 27 DF, p-value: 4.589e-11