Exam Homework

TASK 1

Task 1.1

Introduction

The data was extracted from the 1974 Motor Trend US magazine compiling 10 aspects of automobile design and performance for 32 automobiles between years 1973 and 1974. 8 variables are quantitative with 2 being qualitative.

Original imported variables:

  • mpg: Miles/(US) gallon
  • cyl: Number of cylinders
  • disp: Displacement (cu.in.)
  • hp: Gross horsepower
  • drat: Rear axle ratio
  • wt: Weight (1000 lbs)
  • qsec: 1/4 mile time
  • vs: Engine (0 = V-shaped, 1 = straight)
  • am: Transmission (0 = automatic, 1 = manual)
  • gear: Number of forward gears
  • carb: Number of carburetors

Modified variables for better understanding:

  • Model: Car model name
  • MPG: Miles Per Gallon is the American unit of measure of fuel consumption equivalent to L/100km in Europe.
  • Cylinders: Number of cylinders in the internal combustion engine
  • Displacement: Engine displacement size in cubic inches
  • Horsepower: Power output of the engine in horsepower
  • Weight: Weight of the vehicle in pounds
  • Transmission: Type of transmission (Manual & Automatic)
  • Gears: Number of transmission gears

Task 1.2

Importing data

mydata <- read.table("./mtcars.csv", 
                     header = TRUE, 
                     sep = ",",
                     dec = ".")

head(mydata)
##               model  mpg cyl disp  hp drat    wt  qsec vs am gear
## 1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4
## 2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4
## 3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4
## 4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3
## 5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3
## 6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3
##   carb
## 1    4
## 2    4
## 3    1
## 4    1
## 5    2
## 6    1

Deleting unwanted variables and renaming descriptions

mydata$drat <- NULL
mydata$qsec <- NULL
mydata$vs <- NULL
mydata$carb <- NULL

names(mydata) <- c("Model", "MPG", "Cylinders", "Displacement", "Horsepower", "Weight", "Transmission", "Gears")

head(mydata)
##               Model  MPG Cylinders Displacement Horsepower Weight
## 1         Mazda RX4 21.0         6          160        110  2.620
## 2     Mazda RX4 Wag 21.0         6          160        110  2.875
## 3        Datsun 710 22.8         4          108         93  2.320
## 4    Hornet 4 Drive 21.4         6          258        110  3.215
## 5 Hornet Sportabout 18.7         8          360        175  3.440
## 6           Valiant 18.1         6          225        105  3.460
##   Transmission Gears
## 1            1     4
## 2            1     4
## 3            1     4
## 4            0     3
## 5            0     3
## 6            0     3

Changing the Transmission value type from numerical to categorical

mydata$Transmission <- factor(mydata$Transmission, 
                              levels = c(0, 1), 
                              labels = c("Automatic", "Manual"))
print(mydata$Transmission)
##  [1] Manual    Manual    Manual    Automatic Automatic Automatic
##  [7] Automatic Automatic Automatic Automatic Automatic Automatic
## [13] Automatic Automatic Automatic Automatic Automatic Manual   
## [19] Manual    Manual    Automatic Automatic Automatic Automatic
## [25] Automatic Manual    Manual    Manual    Manual    Manual   
## [31] Manual    Manual   
## Levels: Automatic Manual

Convert weight from pounds to tons for all vehicles and generating a table

mydata$Weight <- mydata$Weight * 0.453592 #Conversion factor

head(mydata)
##               Model  MPG Cylinders Displacement Horsepower   Weight
## 1         Mazda RX4 21.0         6          160        110 1.188411
## 2     Mazda RX4 Wag 21.0         6          160        110 1.304077
## 3        Datsun 710 22.8         4          108         93 1.052333
## 4    Hornet 4 Drive 21.4         6          258        110 1.458298
## 5 Hornet Sportabout 18.7         8          360        175 1.560356
## 6           Valiant 18.1         6          225        105 1.569428
##   Transmission Gears
## 1       Manual     4
## 2       Manual     4
## 3       Manual     4
## 4    Automatic     3
## 5    Automatic     3
## 6    Automatic     3

Removing identical values of horsepower of similar cars

MT_Cars <- mydata[!duplicated(mydata$Horsepower), ]

head(MT_Cars)
##               Model  MPG Cylinders Displacement Horsepower   Weight
## 1         Mazda RX4 21.0         6        160.0        110 1.188411
## 3        Datsun 710 22.8         4        108.0         93 1.052333
## 5 Hornet Sportabout 18.7         8        360.0        175 1.560356
## 6           Valiant 18.1         6        225.0        105 1.569428
## 7        Duster 360 14.3         8        360.0        245 1.619323
## 8         Merc 240D 24.4         4        146.7         62 1.446958
##   Transmission Gears
## 1       Manual     4
## 3       Manual     4
## 5    Automatic     3
## 6    Automatic     3
## 7    Automatic     3
## 8    Automatic     4

Creating new dataframe with only Mercedes models

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
Mercedes <- mydata %>%
  filter(grepl("Merc", Model))

head(Mercedes)
##        Model  MPG Cylinders Displacement Horsepower   Weight
## 1  Merc 240D 24.4         4        146.7         62 1.446958
## 2   Merc 230 22.8         4        140.8         95 1.428815
## 3   Merc 280 19.2         6        167.6        123 1.560356
## 4  Merc 280C 17.8         6        167.6        123 1.560356
## 5 Merc 450SE 16.4         8        275.8        180 1.846119
## 6 Merc 450SL 17.3         8        275.8        180 1.691898
##   Transmission Gears
## 1    Automatic     4
## 2    Automatic     4
## 3    Automatic     4
## 4    Automatic     4
## 5    Automatic     3
## 6    Automatic     3

Task 1.3

Descriptive statistics of dataset for MPG and Horsepower

summary(mydata$MPG)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   10.40   15.43   19.20   20.09   22.80   33.90
summary(mydata$Horsepower)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    52.0    96.5   123.0   146.7   180.0   335.0

The results above show the minimum, maximum, median, mean and the quartiles of the chosen two variables.

The MPG (Miles per Gallon) median value of 19.20 is the middle number of a data set when put into order.

The horsepower mean value of 146.7 describes the average horsepower of the 32 observed values in the data set.

cor(mydata[ , c("MPG", "Horsepower")])
##                   MPG Horsepower
## MPG         1.0000000 -0.7761684
## Horsepower -0.7761684  1.0000000

The negative strong correlation of -0.78 between the variables indicates that the a higher horsepower value has a strong negative influence on the MPG value.

Detailed statistical description with a different function

library(psych)
describe.by(mydata)
## Warning: describe.by is deprecated.  Please use the describeBy
## function
## Warning in describeBy(x = x, group = group, mat = mat, type = type,
## ...): no grouping variable requested
##               vars  n   mean     sd median trimmed    mad   min
## Model*           1 32  16.50   9.38  16.50   16.50  11.86  1.00
## MPG              2 32  20.09   6.03  19.20   19.70   5.41 10.40
## Cylinders        3 32   6.19   1.79   6.00    6.23   2.97  4.00
## Displacement     4 32 230.72 123.94 196.30  222.52 140.48 71.10
## Horsepower       5 32 146.69  68.56 123.00  141.19  77.10 52.00
## Weight           6 32   1.46   0.44   1.51    1.43   0.35  0.69
## Transmission*    7 32   1.41   0.50   1.00    1.38   0.00  1.00
## Gears            8 32   3.69   0.74   4.00    3.62   1.48  3.00
##                  max  range  skew kurtosis    se
## Model*         32.00  31.00  0.00    -1.31  1.66
## MPG            33.90  23.50  0.61    -0.37  1.07
## Cylinders       8.00   4.00 -0.17    -1.76  0.32
## Displacement  472.00 400.90  0.38    -1.21 21.91
## Horsepower    335.00 283.00  0.73    -0.14 12.12
## Weight          2.46   1.77  0.42    -0.02  0.08
## Transmission*   2.00   1.00  0.36    -1.92  0.09
## Gears           5.00   2.00  0.53    -1.07  0.13

Task 1.4

Creating a graphical representaition of data

library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
## The following object is masked from 'package:dplyr':
## 
##     recode
mydata_scatter <- mydata[, c(-1,-7)] #Removed variables Model and Transmission due to irrelevance

scatterplotMatrix(mydata_scatter, 
                  smooth = FALSE)

The above scatterplots with regression lines show the correlation between the selected variables. Variables “Transmission” and “Model” were removed due to irrelevance.

Correlation matrix for the above scatterplots

library(Hmisc)
## 
## Attaching package: 'Hmisc'
## The following object is masked from 'package:psych':
## 
##     describe
## The following objects are masked from 'package:dplyr':
## 
##     src, summarize
## The following objects are masked from 'package:base':
## 
##     format.pval, units
rcorr(as.matrix(mydata_scatter))
##                MPG Cylinders Displacement Horsepower Weight Gears
## MPG           1.00     -0.85        -0.85      -0.78  -0.87  0.48
## Cylinders    -0.85      1.00         0.90       0.83   0.78 -0.49
## Displacement -0.85      0.90         1.00       0.79   0.89 -0.56
## Horsepower   -0.78      0.83         0.79       1.00   0.66 -0.13
## Weight       -0.87      0.78         0.89       0.66   1.00 -0.58
## Gears         0.48     -0.49        -0.56      -0.13  -0.58  1.00
## 
## n= 32 
## 
## 
## P
##              MPG    Cylinders Displacement Horsepower Weight Gears 
## MPG                 0.0000    0.0000       0.0000     0.0000 0.0054
## Cylinders    0.0000           0.0000       0.0000     0.0000 0.0042
## Displacement 0.0000 0.0000                 0.0000     0.0000 0.0010
## Horsepower   0.0000 0.0000    0.0000                  0.0000 0.4930
## Weight       0.0000 0.0000    0.0000       0.0000            0.0005
## Gears        0.0054 0.0042    0.0010       0.4930     0.0005

Create a scatterplot for variables MPG and Horsepower

scatterplot(MPG ~ Horsepower, data = mydata, 
            main = "Scatterplot of MPG vs. Horsepower",
            xlab = "Horsepower",
            ylab = "MPG",
            pch = 1,  # Point character
            col = "purple",  # Point color
            smooth = FALSE)  # Regression line

The above scatter plot presents the relationship between MPG and Horsepower. As concluded from the correlation calculation above, the graphical representation shows the negative correlation between the variables with a downward sloping regression line. The box plots show the distribution of the values of MPG and Horsepower. While the variable of MPG has no clear outliers, the Horsepower variable has one evident outlier that can be found in the lower right handside of the scatterplot.

Distribution of MPG data

hist(mydata$MPG, 
     xlab = "Miles per Gallon (MPG)", 
     ylab = "Frequency", 
     main = "Histogram of MPG values")

The histogram indicates signs of a bimodal distribution of MPG values with a higher and a lower peak.

Cooks distance calculation for identification of potential outliers

mydata_new <- lm(MPG ~ Horsepower,
           data = mydata)

mydata$CooksD <- round(cooks.distance(mydata_new), 3) #Cooks distances

head(mydata[order(-mydata$CooksD),], 6) #Generate table
##                 Model  MPG Cylinders Displacement Horsepower
## 31      Maserati Bora 15.0         8        301.0        335
## 20     Toyota Corolla 33.9         4         71.1         65
## 18           Fiat 128 32.4         4         78.7         66
## 28       Lotus Europa 30.4         4         95.1        113
## 29     Ford Pantera L 15.8         8        351.0        264
## 15 Cadillac Fleetwood 10.4         8        472.0        205
##       Weight Transmission Gears CooksD
## 31 1.6193234       Manual     5  1.052
## 20 0.8323413       Manual     4  0.206
## 18 0.9979024       Manual     4  0.138
## 28 0.6862847       Manual     5  0.091
## 29 1.4378866       Manual     5  0.076
## 15 2.3813580    Automatic     3  0.067

The table shoes that the car with number 31 (Maserati Bora) has a cooks value higher than 1, indicating high influence on the whole dataset.

Removing model number 31 (Maserati Bora) from dataset

library(dplyr)

mydata_new <- mydata %>%
  filter(!Model == ("Maserati Bora"))

tail(mydata_new, 6)
##             Model  MPG Cylinders Displacement Horsepower    Weight
## 26      Fiat X1-9 27.3         4         79.0         66 0.8777005
## 27  Porsche 914-2 26.0         4        120.3         91 0.9706869
## 28   Lotus Europa 30.4         4         95.1        113 0.6862847
## 29 Ford Pantera L 15.8         8        351.0        264 1.4378866
## 30   Ferrari Dino 19.7         6        145.0        175 1.2564498
## 31     Volvo 142E 21.4         4        121.0        109 1.2609858
##    Transmission Gears CooksD
## 26       Manual     4  0.009
## 27       Manual     5  0.009
## 28       Manual     5  0.091
## 29       Manual     5  0.076
## 30       Manual     5  0.003
## 31       Manual     4  0.002

TASK 2

Importing data

Bodymass <- read.table("~/Other/Documents/Education/University/IMB/Bootcamp/R Take Home Exam/Task 2/Body mass.csv", 
                       header= TRUE , 
                       sep = ";", 
                       dec=",")
head(Bodymass, 10)
##    ID Mass
## 1   1 62.1
## 2   2 64.5
## 3   3 56.5
## 4   4 53.4
## 5   5 61.3
## 6   6 62.2
## 7   7 62.7
## 8   8 64.5
## 9   9 59.5
## 10 10 68.9

Task 2.1

Descriptive statistics

summary(Bodymass)
##        ID             Mass      
##  Min.   : 1.00   Min.   :49.70  
##  1st Qu.:13.25   1st Qu.:60.23  
##  Median :25.50   Median :62.80  
##  Mean   :25.50   Mean   :62.88  
##  3rd Qu.:37.75   3rd Qu.:64.50  
##  Max.   :50.00   Max.   :83.20
head(Bodymass)
##   ID Mass
## 1  1 62.1
## 2  2 64.5
## 3  3 56.5
## 4  4 53.4
## 5  5 61.3
## 6  6 62.2

Generating histogram

hist(Bodymass$Mass,
     xlab = "Student Bodymass",
     main = "Bodymass Distribution")

The graph shows a normal distribution with most of the students weighing between 60 and 65 kilograms.

Testing Null hypothesis

H0:𝜇= 59.5 H1:𝜇≠ 59.5

t.test(Bodymass$Mass,
       paired = FALSE,
       mu = 59.5,
       alternative ="two.sided")
## 
##  One Sample t-test
## 
## data:  Bodymass$Mass
## t = 3.9711, df = 49, p-value = 0.000234
## alternative hypothesis: true mean is not equal to 59.5
## 95 percent confidence interval:
##  61.16758 64.58442
## sample estimates:
## mean of x 
##    62.876

The results of the one sample t-test provide strong evidence against the null hypothesis. There is a significant distinction between the sample mean (62.9 kg) and the hypothesized population mean (59.5 kg). The p-value of 0.000234 indicates that the probability of the observing the values outside the interval is 0.0234% (lower than 5%). The confidence interval of 61.2 and 64.6 indicates the 95% confidence of the real population mean falling between the two values. Based on the results we can accept the alternative hypothesis H1.

Interpreting the effect size

library(effectsize)
## 
## Attaching package: 'effectsize'
## The following object is masked from 'package:psych':
## 
##     phi
cohens_d(Bodymass$Mass, mu=59.5)
## Cohen's d |       95% CI
## ------------------------
## 0.56      | [0.26, 0.86]
## 
## - Deviation from a difference of 59.5.
interpret_cohens_d(0.56, rules = "sawilowsky2009")
## [1] "medium"
## (Rules: sawilowsky2009)

Considering the interpretation of the standardized differences according to Sawilowsky (2009), we can observe a medium deviation in mass indicated by the value of 0.56.

TASK 3

Import the dataset Apartments.xlsx

library(readxl)
Apartments <- read_xlsx("~/Other/Documents/Education/University/IMB/Bootcamp/R Take Home Exam/Task 3/Apartments.xlsx")

Apartments <- as.data.frame(Apartments) 

head(Apartments)
##   Age Distance Price Parking Balcony
## 1   7       28  1640       0       1
## 2  18        1  2800       1       0
## 3   7       28  1660       0       0
## 4  28       29  1850       0       1
## 5  18       18  1640       1       1
## 6  28       12  1770       0       1

Description:

  • Age: Age of an apartment in years
  • Distance: The distance from city center in km
  • Price: Price per m2
  • Parking: 0-No, 1-Yes
  • Balcony: 0-No, 1-Yes

Change categorical variables into factors.

Apartments$ParkingFactor <- factor(Apartments$Parking, 
                              levels = c(0, 1), 
                              labels = c("No", "Yes"))

Apartments$BalconyFactor <- factor(Apartments$Balcony, 
                              levels = c(0, 1), 
                              labels = c("No", "Yes"))

head(Apartments, 3)
##   Age Distance Price Parking Balcony ParkingFactor BalconyFactor
## 1   7       28  1640       0       1            No           Yes
## 2  18        1  2800       1       0           Yes            No
## 3   7       28  1660       0       0            No            No

Test the hypothesis H0: Mu_Price = 1900 eur. What can you conclude?

t.test(Apartments$Price,
       paired = FALSE,
       mu = 1900,
       alternative ="two.sided")
## 
##  One Sample t-test
## 
## data:  Apartments$Price
## t = 2.9022, df = 84, p-value = 0.004731
## alternative hypothesis: true mean is not equal to 1900
## 95 percent confidence interval:
##  1937.443 2100.440
## sample estimates:
## mean of x 
##  2018.941

As the p-value of 0.004 is bellow the allowed threshold of 0.05, we can reject the null hypothesis and accept the alternative. The average apartment price per squared meter is 2018.94 EUR.

Estimate the simple regression function: Price = f(Age). Save results in object fit1 and explain the estimate of regression coefficient, coefficient of correlation and coefficient of determination.

fit1 <- lm(Price ~ Age,
           data = Apartments)

summary(fit1)
## 
## Call:
## lm(formula = Price ~ Age, data = Apartments)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -623.9 -278.0  -69.8  243.5  776.1 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2185.455     87.043  25.108   <2e-16 ***
## Age           -8.975      4.164  -2.156    0.034 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 369.9 on 83 degrees of freedom
## Multiple R-squared:  0.05302,    Adjusted R-squared:  0.04161 
## F-statistic: 4.647 on 1 and 83 DF,  p-value: 0.03401
cor(Apartments$Price, Apartments$Age)
## [1] -0.230255
library(car)
scatterplot(Apartments$Price ~ Apartments$Age, 
            ylab = "Price per meter squared", 
            xlab = "Age of Apartment", 
            smooth = FALSE, 
            boxplots = FALSE,
            col = "red",
            data = Apartments)

Estimate of the Regression Coefficient: The value of 2185.46 represents the y-intercept indicating the mean price per m2 at age 0. The value of -8.98 indicates that for every 1 year of age the price per m2 decreases by 8.98 EUR.

Coefficient of Correlation: The coefficient of correlation shows a weak negative correlation between Age and Price indicated by the value of -0.23.

Coefficient of determination: The R squared value of 0.053 indicates that there is a 5.3% variability in prices per m2 influenced by their age.

Show the scateerplot matrix between Price, Age and Distance. Based on the matrix determine if there is potential problem with multicolinearity.

library(car)
scatterplotMatrix(Apartments[ , c(-4,-5,-6,-7)],
                  smooth = FALSE) 

library(Hmisc)
rcorr(as.matrix(Apartments[ , c(-4, -5, -6, -7)]))
##            Age Distance Price
## Age       1.00     0.04 -0.23
## Distance  0.04     1.00 -0.63
## Price    -0.23    -0.63  1.00
## 
## n= 85 
## 
## 
## P
##          Age    Distance Price 
## Age             0.6966   0.0340
## Distance 0.6966          0.0000
## Price    0.0340 0.0000

The explanatory variables being Age and Distance appear weakly correlated supported with a value of 0.04, therefore there is not need for a multicolinearity test.

Estimate the multiple regression function: Price = f(Age, Distance). Save it in object named fit2.

fit2 <- lm(Price ~ Age + Distance,
           data = Apartments)
summary(fit2)
## 
## Call:
## lm(formula = Price ~ Age + Distance, data = Apartments)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -603.23 -219.94  -85.68  211.31  689.58 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2460.101     76.632   32.10  < 2e-16 ***
## Age           -7.934      3.225   -2.46    0.016 *  
## Distance     -20.667      2.748   -7.52 6.18e-11 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 286.3 on 82 degrees of freedom
## Multiple R-squared:  0.4396, Adjusted R-squared:  0.4259 
## F-statistic: 32.16 on 2 and 82 DF,  p-value: 4.896e-11

Check the multicolinearity with VIF statistics. Explain the findings.

vif(fit2)
##      Age Distance 
## 1.001845 1.001845

The results confirm our assumption for the multicolinearity of the explanatory variables with the factor of 1.0018. Only a Variance Inflation Factor above 5 would indicate collinearity.

Calculate standardized residuals and Cooks Distances for model fit2. Remove any potentially problematic units (outliers or units with high influence).

Apartments$StdResid <- round(rstandard(fit2), 5) #Standardized residuals
Apartments$CooksD <- round(cooks.distance(fit2), 5) #Cooks distances

hist(Apartments$StdResid, 
     xlab = "Standardized residuals", 
     ylab = "Frequency", 
     main = "Histogram of standardized residuals")

shapiro.test(Apartments$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  Apartments$StdResid
## W = 0.95306, p-value = 0.003661
hist(Apartments$CooksD, 
     xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histogram of Cooks distances")

head(Apartments[order(Apartments$StdResid),], 6) #Six units with lowest value of stand. residuals
##    Age Distance Price Parking Balcony ParkingFactor BalconyFactor
## 53   7        2  1760       0       1            No           Yes
## 13  12       14  1650       0       1            No           Yes
## 72  12       14  1650       0       0            No            No
## 20  13        8  1800       0       0            No            No
## 35  14       16  1660       0       1            No           Yes
## 36  24        5  1830       1       0           Yes            No
##    StdResid  CooksD
## 53 -2.15179 0.06626
## 13 -1.49939 0.01312
## 72 -1.49939 0.01312
## 20 -1.38104 0.01226
## 35 -1.26104 0.00794
## 36 -1.18909 0.01151
head(Apartments[order(-Apartments$CooksD),], 6) #Six units with lowest value of stand. residuals
##    Age Distance Price Parking Balcony ParkingFactor BalconyFactor
## 38   5       45  2180       1       1           Yes           Yes
## 55  43       37  1740       0       0            No            No
## 33   2       11  2790       1       0           Yes            No
## 53   7        2  1760       0       1            No           Yes
## 22  37        3  2540       1       1           Yes           Yes
## 39  40        2  2400       0       1            No           Yes
##    StdResid  CooksD
## 38  2.57677 0.31973
## 55  1.44477 0.10420
## 33  2.05059 0.06913
## 53 -2.15179 0.06626
## 22  1.57598 0.06087
## 39  1.09118 0.03751

Values with ID 38 and ID 55 have a much higher Cooks Distance values of 0.32 and 0.10 standing out in comparison to the others. This observation can be observed on the Cooks Distance histogram. These values will be removed due to high influence. As none of the values in the distribution shown graphically fall beyond the absolute value of 3, there is no need to remove further data.

library(dplyr)
Apartments <- Apartments %>%
  filter(!(Price %in% c("2180", "1740"))) #Filter out influencing values

hist(Apartments$CooksD, 
     xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histogram of Cooks distances")

Despite having another three potential problematic values with a Cooks value of 0.6, they will be ignored as removing them is unnecessary and would yield a lesser precision in the data analysis.

Check for potential heteroskedasticity with scatterplot between standarized residuals and standrdized fitted values. Explain the findings.

fit2 <- lm(Price ~ Age + Distance,
           data = Apartments)

Apartments$StdFitted <- scale(fit2$fitted.values)

library(car)
scatterplot(y = Apartments$StdResid, x = Apartments$StdFitted,
            ylab = "Standardized residuals",
            xlab = "Standardized fitted values",
            boxplots = FALSE,
            regLine = TRUE,
            smooth = FALSE)

The scatterplot indicates nonlinearity and the possibility of heteroskedasticity. To test the assumption a Breusch Pegan test should be performed.

library(olsrr)
## 
## Attaching package: 'olsrr'
## The following object is masked from 'package:datasets':
## 
##     rivers
ols_test_breusch_pagan(fit2)
## 
##  Breusch Pagan Test for Heteroskedasticity
##  -----------------------------------------
##  Ho: the variance is constant            
##  Ha: the variance is not constant        
## 
##               Data                
##  ---------------------------------
##  Response : Price 
##  Variables: fitted values of Price 
## 
##         Test Summary          
##  -----------------------------
##  DF            =    1 
##  Chi2          =    3.775135 
##  Prob > Chi2   =    0.05201969

The value 0.07 being 7% is above the allowed threshold of 5%, therefore we cannot reject the Null Hypothesis H0. The lack of data to reject the null hypothesis indicates our data does not show heteroskedasticity.

Are standardized residuals ditributed normally? Show the graph and formally test it. Explain the findings.

hist(Apartments$StdResid, 
     xlab = "Standardized residuals", 
     ylab = "Frequency", 
     main = "Histogram of Standardized Residuals",
     breaks = seq(from = -3, to = 3, by = 1))

shapiro.test(Apartments$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  Apartments$StdResid
## W = 0.94966, p-value = 0.002646

The data is normally distributed with light right skewness. To test the assumption we use the Sharpio Wilks test.

H0 = Data is normally distributed H1 ≠ Data is not normally distributed

Considering significance level (p-value) of 0.002 is lower than the threshold of 0.05 suggests strong evidence against the null hypothesis. This indicates our data is not normally distributed, meaning we accepted the alternative hypothesis.

Estimate the fit2 again without potentially excluded units and show the summary of the model. Explain all coefficients.

summary(fit2)
## 
## Call:
## lm(formula = Price ~ Age + Distance, data = Apartments)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -627.27 -212.96  -46.23  205.05  578.98 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2490.112     76.189  32.684  < 2e-16 ***
## Age           -7.850      3.244  -2.420   0.0178 *  
## Distance     -23.945      2.826  -8.473 9.53e-13 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 273.5 on 80 degrees of freedom
## Multiple R-squared:  0.4968, Adjusted R-squared:  0.4842 
## F-statistic: 39.49 on 2 and 80 DF,  p-value: 1.173e-12

The summary function now excludes the two influencing variables thus altering the results.

The average price per m2 at age 0 has increased to 2490 EUR. The 1 year age increase insignificantly influences the price increase, remaining at 7.9 EUR. The increasing distance from the center by 1 km increments has further decreased the price to 23.9 EUR per m2. The increased variability now explains the price variability of distance and age for 49% of apartments. The significance level being extremely small indicates significant effect of age and distance on the price per m2.

Estimate the linear regression function Price = f(Age, Distance, Parking and Balcony). Be careful to correctly include categorical variables. Save the object named fit3.

fit3 <- lm(Price ~ Age + Distance + ParkingFactor + BalconyFactor,
           data = Apartments)

With function anova check if model fit3 fits data better than model fit2.

anova(fit2, fit3)
## Analysis of Variance Table
## 
## Model 1: Price ~ Age + Distance
## Model 2: Price ~ Age + Distance + ParkingFactor + BalconyFactor
##   Res.Df     RSS Df Sum of Sq      F  Pr(>F)  
## 1     80 5982100                              
## 2     78 5458696  2    523404 3.7395 0.02813 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

H0 = fit2 is better H1 = fit3 is better

The significance level of 0.02 being lower than 0.05 rejects the null hypothesis and accepts the alternative hypothesis. This shows fit3 fits the data better.

Show the results of fit3 and explain regression coefficient for both categorical variables. Can you write down the hypothesis which is being tested with F-statistics, shown at the bottom of the output?

summary(fit3)
## 
## Call:
## lm(formula = Price ~ Age + Distance + ParkingFactor + BalconyFactor, 
##     data = Apartments)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -499.06 -194.33  -32.04  219.03  544.31 
## 
## Coefficients:
##                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      2358.900     93.664  25.185  < 2e-16 ***
## Age                -7.197      3.148  -2.286  0.02499 *  
## Distance          -21.241      2.911  -7.296 2.14e-10 ***
## ParkingFactorYes  168.921     62.166   2.717  0.00811 ** 
## BalconyFactorYes   -6.985     58.745  -0.119  0.90566    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 264.5 on 78 degrees of freedom
## Multiple R-squared:  0.5408, Adjusted R-squared:  0.5173 
## F-statistic: 22.97 on 4 and 78 DF,  p-value: 1.449e-12

Parking: Apartments with a parking spot increase the price per m2 by 168.92 EUR, assuming all other variables remain the same.The low significance level of 0.008 indicates a strong influence on the price per m2.

Balcony: Apartments with a balcony decrease the price per m2 by 6.99 EUR, assuming all other variables remain the same. The very high significance level of 0.9 indicates non significance in the price per m2 influence.

F-statistics: The statistic tests the significance of regression.

H0 = R squared is equal 0 H1 = R squared is not equal 0

On the basis of the p-value of 0.001 we can reject the null hypothesis. This indicates that there is a linear relationship between price and the explanatory variables.

Save fitted values and calaculate the residual for apartment ID2.

Apartments$Fitted <- fitted.values(fit3)
Apartments$Residuals <- residuals(fit3)

head(Apartments[colnames(Apartments) %in% c("Price", "Fitted", "Residuals")], 2)
##   Price   Fitted Residuals
## 1  1640 1706.795 -66.79523
## 2  2800 2377.043 422.95718

The apartment with ID2 has a fitted value of 2377 compared to the actual value of 2800.