Simple Linear Regression with R

Q1 Read Tombstone data into R #To read the data into R, I used the below command. I also renamed column 2 and 3.

tombstone <- read.csv("tombstone.csv", h=T)
colnames(tombstone)[2] <- "Mean SO2 Concentration"
colnames(tombstone)[3] <- "Mean Surface Recession Rate"
tombstone
##                     City Mean SO2 Concentration Mean Surface Recession Rate
## 1  Washington,DC (Rural)                     12                        0.27
## 2  Cincinnati,OH (Rural)                     20                        0.14
## 3  Philadelphia,PA (Rura                     20                        0.33
## 4            Richmond,VA                     46                        0.81
## 5          Fall River,MA                     48                        0.84
## 6            Hartford,CT                     92                        1.08
## 7            Evanston,IL                     91                        1.78
## 8              Albany,NY                     94                        1.21
## 9          Washington,DC                    102                        1.09
## 10         Louisville,KY                    117                        1.72
## 11         Providence,RI                    122                        1.18
## 12          Cambridge,MA                    142                        1.01
## 13          Baltimore,MD                    142                        1.90
## 14             Newark,NJ                    178                        1.98
## 15             Boston,MA                    180                        1.53
## 16         Pittsburgh,PA                    197                        2.71
## 17         Cincinnati,OH                    224                        2.41
## 18           Brooklyn,NY                    234                        1.61
## 19       Philadelphia,PA                    239                        2.51
## 20       Indianapolis,IN                    244                        2.15
## 21            Chicago,IL                    323                        3.16

Q2. Plot data, explore data, and briefly describe what you observe.

str(tombstone)
## 'data.frame':    21 obs. of  3 variables:
##  $ City                       : chr  "Washington,DC (Rural)" "Cincinnati,OH (Rural)" "Philadelphia,PA (Rura" "Richmond,VA" ...
##  $ Mean SO2 Concentration     : int  12 20 20 46 48 92 91 94 102 117 ...
##  $ Mean Surface Recession Rate: num  0.27 0.14 0.33 0.81 0.84 1.08 1.78 1.21 1.09 1.72 ...

The dataset contains information about 21 cities in rural and urban areas providing insights into the air quality and pollution levels(S02 concentration) and the rate at which surfaces in these areas are undergoing recession.

summary(tombstone)
##      City           Mean SO2 Concentration Mean Surface Recession Rate
##  Length:21          Min.   : 12.0          Min.   :0.140              
##  Class :character   1st Qu.: 91.0          1st Qu.:1.010              
##  Mode  :character   Median :122.0          Median :1.530              
##                     Mean   :136.5          Mean   :1.496              
##                     3rd Qu.:197.0          3rd Qu.:1.980              
##                     Max.   :323.0          Max.   :3.160

Based on the summary, we see that the lowest amount of mean C02 concentration recorded was 12 and the highest was 323 and most cities had a concentration between 91 and 197. We also see that the slowest recession rate observed was 0.14 while the fastest was 3.160. About half of the cities had rates betwwen 1.010 and 1.980.

hist(tombstone$`Mean SO2 Concentration`, main = "Distribution of Mean SO2 Concentration")

hist(tombstone$`Mean Surface Recession Rate`, main = "Distribution of Mean Surface Recession Rate")

We can see that there’s almost a normal distribution with some skewness in both SO2 concentration and recession rate.

plot(tombstone$"Mean SO2 Concentration", tombstone$"Mean Surface Recession Rate", pch = 20,
     xlab = "Mean SO2 Concentration", ylab = "Mean Surface Recession Rate",
     main = "Mean SO2 Concentration vs. Surface Recession Rate")

From the plot above we can see that there seem to be positive linear relationship between the two variables where as the S02 concentration increases, recession rate also increases.

Q3. Perform linear regression using lm() function I first created the regression model

plot(tombstone$"Mean SO2 Concentration", tombstone$"Mean Surface Recession Rate", pch = 20,
     xlab = "Mean SO2 Concentration", ylab = "Mean Surface Recession Rate",
     main = "Mean SO2 Concentration vs. Surface Recession Rate")

model <- lm(`Mean Surface Recession Rate` ~ `Mean SO2 Concentration`, data = tombstone)
model
## 
## Call:
## lm(formula = `Mean Surface Recession Rate` ~ `Mean SO2 Concentration`, 
##     data = tombstone)
## 
## Coefficients:
##              (Intercept)  `Mean SO2 Concentration`  
##                 0.322996                  0.008593
abline(model, col = "blue")

Q3.1 Obtain coefficient estimates β^0 and β^1.

model$coefficients
##              (Intercept) `Mean SO2 Concentration` 
##              0.322995899              0.008593333
  Q3.2 Obtain fitted values and the sum of fitted values. 
fitted_values <- predict(model)
fitted_values
##         1         2         3         4         5         6         7         8 
## 0.4261159 0.4948626 0.4948626 0.7182892 0.7354759 1.1135825 1.1049892 1.1307692 
##         9        10        11        12        13        14        15        16 
## 1.1995159 1.3284159 1.3713825 1.5432492 1.5432492 1.8526092 1.8697959 2.0158825 
##        17        18        19        20        21 
## 2.2479025 2.3338359 2.3768025 2.4197692 3.0986425
sum_fitted_values <- sum(fitted_values)
sum_fitted_values
## [1] 31.42
  Q3.3 Obtain the sum of all values of response variable
sum(tombstone$`Mean Surface Recession Rate`)
## [1] 31.42
  Q3.4 Verify the fact that the sum of fitted values is always the same as the sum of response variable. In addition, verify the fact that the mean of the fitted values is always the same as the mean of response variable.
sum_fitted_values <- sum(fitted_values)
sum_fitted_values
## [1] 31.42
sum_response_variable <- sum(tombstone$`Mean Surface Recession Rate`)
sum_response_variable
## [1] 31.42
mean_fitted_values <- mean(fitted_values)
mean_fitted_values
## [1] 1.49619
mean_response_variable <- mean(tombstone$`Mean Surface Recession Rate`)
mean_response_variable
## [1] 1.49619
if (isTRUE(all.equal(sum_fitted_values, sum_response_variable))) {
 print("The sum of fitted values is equal to sum of response variable")
} else {
  print("The sum of fitted values is not equal to sum of response variable")
}
## [1] "The sum of fitted values is equal to sum of response variable"
if (isTRUE(all.equal(mean_fitted_values, mean_response_variable))) {
  print("The sum of fitted values is equal to sum of response variable")
} else {
  print("The sum of fitted values is not equal to sum of response variable")
}
## [1] "The sum of fitted values is equal to sum of response variable"
Q3.5 Obtain residuals and the sum of residuals, and verify the fact that the sum of residuals is always zero.
model$residuals
##           1           2           3           4           5           6 
## -0.15611590 -0.35486256 -0.16486256  0.09171078  0.10452411 -0.03358255 
##           7           8           9          10          11          12 
##  0.67501079  0.07923079 -0.10951588  0.39158412 -0.19138254 -0.53324921 
##          13          14          15          16          17          18 
##  0.35675079  0.12739080 -0.33979586  0.69411747  0.16209748 -0.72383585 
##          19          20          21 
##  0.13319748 -0.26976919  0.06135750
sum_of_residuals <- sum(model$residuals)
sum_of_residuals
## [1] 5.065393e-16
round(sum_of_residuals,8)
## [1] 0
  Q3.6 Obtain the standard errors of β^0 and β^1. Are these standard errors satisfactory and why?

To understand the standard error, we need to understand its proportion with the estimate value. for intercept estimated value is 0.322 and the std error is 0.15 meaning the fraction is about 46% - this seems to be a high std error there’s a large variation on this intercept. estimation on the intercept is high. however for slope std error is 0.0009, the fraction in relation to the estimate is about 10% meaning the coeffcient estimate is precise due to this the standard error is satisfactory

summary_model <- summary(model)
summary_model
## 
## Call:
## lm(formula = `Mean Surface Recession Rate` ~ `Mean SO2 Concentration`, 
##     data = tombstone)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.72384 -0.19138  0.06136  0.13320  0.69412 
## 
## Coefficients:
##                           Estimate Std. Error t value Pr(>|t|)    
## (Intercept)              0.3229959  0.1521958   2.122   0.0472 *  
## `Mean SO2 Concentration` 0.0085933  0.0009499   9.046 2.58e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.365 on 19 degrees of freedom
## Multiple R-squared:  0.8116, Adjusted R-squared:  0.8017 
## F-statistic: 81.83 on 1 and 19 DF,  p-value: 2.579e-08
B0 <- summary_model$coefficients[1, 2]
B0
## [1] 0.1521958
B1 <- summary_model$coefficients[2, 2]
B1
## [1] 0.0009499341

Q4 Suppose we increase SO2 Concentration by one unit, how does such a change influence the Surface Recession Rate?

Given the estimate for the slope is 0.008593, this means that the Surface Recession Rate will increase by 0.008593 for every one unit increase of SO2 Concentration.

Q5 Does the intercept of the linear regression have natural interpretation? If so, what does it mean?

Yes, The intercept in a linear regression model has a natural interpretation. It represents the estimated value of the Surface Recession Rate when S02 concentration is set to zero. interpretation is that the Surface Recession Rate = 0.3229959+0.0085933 * S02 Concentration level, meaning if we have 0 concentration level we are estimation a surface recession rate of 0.3229959

Q6 Which city has the highest Surface Recession Rate?

tombstone[which.max(tombstone$'Mean Surface Recession Rate'), "City"]
## [1] "Chicago,IL"

Q7 Which city has the largest residual (i.e., the largest absolute value) according to the linear regression you just fitted?

largest_residuals <- tombstone$'Mean Surface Recession Rate' - fitted(model)
abs_residuals <- abs(largest_residuals)
max_index <- which.max(abs_residuals)
city_name <- tombstone$'City'[max_index]
city_name
## [1] "Brooklyn,NY"

Q8. Calculate the mean of covariate (x^mean) and mean of response (y^mean). Verify the fact that the fitted regression line go through the point (x^mean, y^mean).

x_mean <- mean(tombstone$"Mean SO2 Concentration")
x_mean
## [1] 136.5238
y_mean <- mean(tombstone$"Mean Surface Recession Rate")
y_mean
## [1] 1.49619
plot(tombstone$"Mean SO2 Concentration", tombstone$"Mean Surface Recession Rate", pch = 18,
     xlab = "Mean SO2 Concentration", ylab = "Mean Surface Recession Rate",
     main = "Mean SO2 Concentration vs. Surface Recession Rate")

model <- lm(`Mean Surface Recession Rate` ~ `Mean SO2 Concentration`, data = tombstone)
model
## 
## Call:
## lm(formula = `Mean Surface Recession Rate` ~ `Mean SO2 Concentration`, 
##     data = tombstone)
## 
## Coefficients:
##              (Intercept)  `Mean SO2 Concentration`  
##                 0.322996                  0.008593
abline(model, col = "blue")

points(x=x_mean, y=y_mean, col="red", pch=15)

Read Bus data into R

bus <- read.csv("bus.csv", h=T)
bus
##    Expenses.per.car.mile..pence. Car.miles.per.year..1000s.
## 1                          19.76                       6235
## 2                          17.85                      46230
## 3                          19.96                       7360
## 4                          16.80                      28715
## 5                          18.20                      21934
## 6                          16.71                       1337
## 7                          18.81                      17881
## 8                          20.74                       2319
## 9                          16.56                      18040
## 10                         18.55                       1147
## 11                         17.40                       2176
## 12                         17.62                      13267
## 13                         21.24                       3581
## 14                         18.23                      15104
## 15                         16.86                      47009
## 16                         17.45                      10139
## 17                         17.66                       6147
## 18                         18.30                      23089
## 19                         16.58                      20550
## 20                         17.51                       9450
## 21                         21.17                       1028
## 22                         16.92                       3848
## 23                         16.96                      15656
## 24                         18.24                       7725
##    Percent.of.Double.Deckers.in.fleet Percent.of.fleet.on.fuel.oil
## 1                              100.00                       100.00
## 2                               43.67                        84.53
## 3                               65.51                        81.57
## 4                               45.16                        93.33
## 5                               49.20                        83.07
## 6                               74.84                        94.99
## 7                               70.66                        92.34
## 8                               63.93                        95.08
## 9                               14.45                        61.24
## 10                              68.58                        97.90
## 11                              53.33                        97.50
## 12                              25.16                        56.86
## 13                              35.76                        63.58
## 14                              47.72                        95.29
## 15                              17.21                       100.00
## 16                              43.15                        89.40
## 17                              67.73                        92.54
## 18                              33.27                        67.53
## 19                              26.61                        98.32
## 20                              61.35                        86.72
## 21                             100.00                       100.00
## 22                               5.35                        65.58
## 23                              20.53                        93.72
## 24                              50.59                        96.63
##    Receipts.per.car.mile..pence.
## 1                          25.10
## 2                          19.23
## 3                          21.42
## 4                          18.11
## 5                          19.24
## 6                          19.31
## 7                          20.07
## 8                          24.35
## 9                          17.60
## 10                         20.13
## 11                         18.40
## 12                         18.96
## 13                         25.75
## 14                         19.40
## 15                         18.64
## 16                         19.10
## 17                         20.00
## 18                         19.31
## 19                         20.49
## 20                         17.07
## 21                         20.61
## 22                         15.73
## 23                         18.70
## 24                         18.99
colnames(bus)[1] <- "Expenses per car mile (pence)"
colnames(bus)[2] <- "Car miles per year (1000s)"

Q2. Plot data, explore data, and briefly describe what you observe.

str(bus)
## 'data.frame':    24 obs. of  5 variables:
##  $ Expenses per car mile (pence)     : num  19.8 17.9 20 16.8 18.2 ...
##  $ Car miles per year (1000s)        : int  6235 46230 7360 28715 21934 1337 17881 2319 18040 1147 ...
##  $ Percent.of.Double.Deckers.in.fleet: num  100 43.7 65.5 45.2 49.2 ...
##  $ Percent.of.fleet.on.fuel.oil      : num  100 84.5 81.6 93.3 83.1 ...
##  $ Receipts.per.car.mile..pence.     : num  25.1 19.2 21.4 18.1 19.2 ...
summary(bus)
##  Expenses per car mile (pence) Car miles per year (1000s)
##  Min.   :16.56                 Min.   : 1028             
##  1st Qu.:16.95                 1st Qu.: 3781             
##  Median :17.75                 Median : 9794             
##  Mean   :18.17                 Mean   :13749             
##  3rd Qu.:18.61                 3rd Qu.:18668             
##  Max.   :21.24                 Max.   :47009             
##  Percent.of.Double.Deckers.in.fleet Percent.of.fleet.on.fuel.oil
##  Min.   :  5.35                     Min.   : 56.86              
##  1st Qu.: 31.61                     1st Qu.: 82.69              
##  Median : 48.46                     Median : 92.94              
##  Mean   : 49.32                     Mean   : 86.99              
##  3rd Qu.: 66.06                     3rd Qu.: 96.85              
##  Max.   :100.00                     Max.   :100.00              
##  Receipts.per.car.mile..pence.
##  Min.   :15.73                
##  1st Qu.:18.68                
##  Median :19.27                
##  Mean   :19.82                
##  3rd Qu.:20.22                
##  Max.   :25.75

we can see the summary of key metrics including average expenses per car mile, car miles per year, the percentage of double deckers in the fleet, and the percentage of the fleet using fuel oil.

hist(bus$`Car miles per year (1000s)`, main = "Distribution of Car miles per year (1000s)")

hist(bus$`Expenses per car mile (pence)`, main = "Distribution of Expenses per car mile (pence)")

We can see that there’s almost a normal distribution with right skewness in both variables meaning the majority of the data is located on the left side of the graph, and the mean is greater than the median

plot(bus$"Car miles per year (1000s)", bus$"Expenses per car mile (pence)", pch = 20,
     xlab = "Car miles per year (1000s)", ylab = "Expenses per car mile (pence)",
     main = "Car miles per year (1000s) vs. Expenses per car mile (pence)")

From the plot above we can see that alot of data is on the left and also as the Car miles increases the expenses per car mile decreases meaning theres a negative relationship

Q3. Perform linear regression using lm() function I first created the regression model

plot(bus$"Car miles per year (1000s)", bus$"Expenses per car mile (pence)", pch = 20,
     xlab = "Car miles per year (1000s)", ylab = "Expenses per car mile (pence)",
     main = "Car miles per year (1000s) vs. Expenses per car mile (pence)")

model2 <- lm(`Expenses per car mile (pence)` ~ `Car miles per year (1000s)`, data = bus)
model2
## 
## Call:
## lm(formula = `Expenses per car mile (pence)` ~ `Car miles per year (1000s)`, 
##     data = bus)
## 
## Coefficients:
##                  (Intercept)  `Car miles per year (1000s)`  
##                   18.7818020                    -0.0000445
abline(model2, col = "blue")

Q3.1 Obtain coefficient estimates β^0 and β^1.

model2$coefficients
##                  (Intercept) `Car miles per year (1000s)` 
##                 1.878180e+01                -4.449914e-05
  Q3.2 Obtain fitted values and the sum of fitted values. 
fitted_values <- fitted(model2)
fitted_values
##        1        2        3        4        5        6        7        8 
## 18.50435 16.72461 18.45429 17.50401 17.80576 18.72231 17.98611 18.67861 
##        9       10       11       12       13       14       15       16 
## 17.97904 18.73076 18.68497 18.19143 18.62245 18.10969 16.68994 18.33063 
##       17       18       19       20       21       22       23       24 
## 18.50827 17.75436 17.86734 18.36129 18.73606 18.61057 18.08512 18.43805
sum_fitted_values <- sum(fitted_values)
sum_fitted_values
## [1] 436.08
  Q3.3 Obtain the sum of all values of response variable
sum(bus$`Expenses per car mile (pence)`)
## [1] 436.08
  Q3.4 Verify the fact that the sum of fitted values is always the same as the sum of response variable. In addition, verify the fact that the mean of the fitted values is always the same as the mean of response variable.
sum_fitted_values <- sum(fitted_values)
sum_fitted_values
## [1] 436.08
sum_response_variable <- sum(bus$ "Expenses per car mile (pence)")
sum_response_variable
## [1] 436.08
mean_fitted_values <- mean(fitted_values)
mean_fitted_values
## [1] 18.17
mean_response_variable <- mean(bus$`Expenses per car mile (pence)`)
mean_response_variable
## [1] 18.17
if (isTRUE(all.equal(sum_fitted_values, sum_response_variable))) {
 print("The sum of fitted values is equal to sum of response variable")
} else {
  print("The sum of fitted values is not equal to sum of response variable")
}
## [1] "The sum of fitted values is equal to sum of response variable"
if (isTRUE(all.equal(mean_fitted_values, mean_response_variable))) {
  print("The sum of fitted values is equal to sum of response variable")
} else {
  print("The sum of fitted values is not equal to sum of response variable")
}
## [1] "The sum of fitted values is equal to sum of response variable"
model2$residuals
##          1          2          3          4          5          6          7 
##  1.2556501  1.1253933  1.5057117 -0.7040092  0.3942422 -2.0123067  0.8238871 
##          8          9         10         11         12         13         14 
##  2.0613915 -1.4190375 -0.1807615 -1.2849719 -0.5714319  2.6175494  0.1203130 
##         15         16         17         18         19         20         21 
##  0.1700581 -0.8806252 -0.8482658  0.5456387 -1.2873447 -0.8512851  2.4339431 
##         22         23         24 
## -1.6905693 -1.1251235 -0.1980461
sum_of_residuals <- sum(model2$residuals)
sum_of_residuals
## [1] 6.106227e-16
round(sum_of_residuals,8)
## [1] 0
  Q3.6 Obtain the standard errors of β^0 and β^1. Are these standard errors satisfactory and why?
  

the standard error is satisfactory

summary_model <- summary(model2)
summary_model
## 
## Call:
## lm(formula = `Expenses per car mile (pence)` ~ `Car miles per year (1000s)`, 
##     data = bus)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -2.0123 -0.9417 -0.1894  0.8993  2.6176 
## 
## Coefficients:
##                                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                   1.878e+01  4.075e-01  46.085   <2e-16 ***
## `Car miles per year (1000s)` -4.450e-05  2.188e-05  -2.034   0.0542 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.347 on 22 degrees of freedom
## Multiple R-squared:  0.1583, Adjusted R-squared:   0.12 
## F-statistic: 4.136 on 1 and 22 DF,  p-value: 0.0542
B0 <- summary_model$coefficients[1, 2]
B0
## [1] 0.4075464
B1 <- summary_model$coefficients[2, 2]
B1
## [1] 2.187948e-05

Q4 Suppose we increase Car Miles by one unit, how does such a change influence the Expenses

Given the estimate for the slope is -4.450e-05, this means that the Expenses will increase by -4.450e-05 for every one unit increase of Car per miles

Q5 Does the intercept of the linear regression have natural interpretation? If so, what does it mean?

In the case the intercept does not have a natural representation due to the Car miles per year cannot equal to zero as it represent total number of miles driven in a year

Q8. Calculate the mean of covariate (x^mean) and mean of response (y^mean). Verify the fact that the fitted regression line go through the point (x^mean, y^mean).

x_mean <- mean(bus$"Car miles per year (1000s)")
x_mean
## [1] 13748.62
y_mean <- mean(bus$"Expenses per car mile (pence)")
y_mean
## [1] 18.17
plot(bus$"Car miles per year (1000s)", bus$"Expenses per car mile (pence)", pch = 20,
     xlab = "Car miles per year (1000s)", ylab = "Expenses per car mile (pence)",
     main = "Car miles per year (1000s) vs. Expenses per car mile (pence)")

model2 <- lm(`Expenses per car mile (pence)` ~ `Car miles per year (1000s)`, data = bus)
model2
## 
## Call:
## lm(formula = `Expenses per car mile (pence)` ~ `Car miles per year (1000s)`, 
##     data = bus)
## 
## Coefficients:
##                  (Intercept)  `Car miles per year (1000s)`  
##                   18.7818020                    -0.0000445
abline(model2, col = "blue")

points(x=x_mean, y=y_mean, col="red", pch=15)