Ivana Tonevska

TASK 1

#data(package = .packages(all.available = TRUE))
library(carData)
mydata <- force(Salaries)
head(mydata)
##        rank discipline yrs.since.phd yrs.service  sex salary
## 1      Prof          B            19          18 Male 139750
## 2      Prof          B            20          16 Male 173200
## 3  AsstProf          B             4           3 Male  79750
## 4      Prof          B            45          39 Male 115000
## 5      Prof          B            40          41 Male 141500
## 6 AssocProf          B             6           6 Male  97000

Explanation of the dataset ‘Salaries for Professors’:

Source: Fox J. and Weisberg, S. (2019) An R Companion to Applied Regression, Third Edition, Sage.
Data for a nine-month academic salary for Assistant Professors, Associate Professors and Professors in a college in the U.S during 2008-09.
There are 397 observations on the following 6 variables:
  * rank:role of the individual in the college (Assistant Professor, Associate Professor or Professor)
  * discipline: A = 'theoretical' departments; B = 'applied' departments
  * yrs.since.phd: years since PhD
  * yrs.service: years of service
  * sex: showing the sex of the individual (Male or Female)
  * salary: nine-month salary, in dollars
  
summary(mydata)
##         rank     discipline yrs.since.phd    yrs.service   
##  AsstProf : 67   A:181      Min.   : 1.00   Min.   : 0.00  
##  AssocProf: 64   B:216      1st Qu.:12.00   1st Qu.: 7.00  
##  Prof     :266              Median :21.00   Median :16.00  
##                             Mean   :22.31   Mean   :17.61  
##                             3rd Qu.:32.00   3rd Qu.:27.00  
##                             Max.   :56.00   Max.   :60.00  
##      sex          salary      
##  Female: 39   Min.   : 57800  
##  Male  :358   1st Qu.: 91000  
##               Median :107300  
##               Mean   :113706  
##               3rd Qu.:134185  
##               Max.   :231545
colnames(mydata)[1] <- "Status" #changing the name of the first column from 'rank' to 'Status'
mydata$disciplineF <- factor(mydata$discipline,
                             levels = c("A", "B"),
                             labels = c("theoretical", "applied"))

#assigning values for 'A' and 'B', while creating a new variable, disciplineF
head(mydata)
##      Status discipline yrs.since.phd yrs.service  sex salary
## 1      Prof          B            19          18 Male 139750
## 2      Prof          B            20          16 Male 173200
## 3  AsstProf          B             4           3 Male  79750
## 4      Prof          B            45          39 Male 115000
## 5      Prof          B            40          41 Male 141500
## 6 AssocProf          B             6           6 Male  97000
##   disciplineF
## 1     applied
## 2     applied
## 3     applied
## 4     applied
## 5     applied
## 6     applied
summary(mydata)[ , -2 ]
##        Status    yrs.since.phd    yrs.service        sex     
##  AsstProf : 67   Min.   : 1.00   Min.   : 0.00   Female: 39  
##  AssocProf: 64   1st Qu.:12.00   1st Qu.: 7.00   Male  :358  
##  Prof     :266   Median :21.00   Median :16.00               
##                  Mean   :22.31   Mean   :17.61               
##                  3rd Qu.:32.00   3rd Qu.:27.00               
##                  Max.   :56.00   Max.   :60.00               
##      salary            disciplineF 
##  Min.   : 57800   theoretical:181  
##  1st Qu.: 91000   applied    :216  
##  Median :107300                    
##  Mean   :113706                    
##  3rd Qu.:134185                    
##  Max.   :231545
  * The highest nine-month salary earned is 231.545dollars, while the average is 113.706dollars
  * yrs.since.phd; median = 21, meaning that half of the professors have had their PhD for less than, or exactly 21 years
  * salary; 3rd Qu = 134185, meaning that 75% of the professors have a salary lower than, or equal to 134185
sum(is.na(mydata)) #count total number of missing values
## [1] 0

There are not any missing values in this dataset

Create a new dataframe containing only those who have been in service for more than 20 years and have a salary higher than 120000.
mydata2 <- mydata[mydata$yrs.service >= 20 & mydata$salary >= 120000, ]
head(mydata2)
##    Status discipline yrs.since.phd yrs.service    sex salary
## 5    Prof          B            40          41   Male 141500
## 7    Prof          B            30          23   Male 175000
## 8    Prof          B            45          45   Male 147765
## 19   Prof          A            37          23   Male 124750
## 20   Prof          A            39          36 Female 137000
## 27   Prof          A            35          23   Male 134885
##    disciplineF
## 5      applied
## 7      applied
## 8      applied
## 19 theoretical
## 20 theoretical
## 27 theoretical

Function stat.desc()

library(pastecs)

round(stat.desc(mydata)[ , c(-1,-2,-5,-7)], 2)
##          yrs.since.phd yrs.service       salary
## nbr.val         397.00      397.00       397.00
## nbr.null          0.00       11.00         0.00
## nbr.na            0.00        0.00         0.00
## min               1.00        0.00     57800.00
## max              56.00       60.00    231545.00
## range            55.00       60.00    173745.00
## sum            8859.00     6993.00  45141464.00
## median           21.00       16.00    107300.00
## mean             22.31       17.61    113706.46
## SE.mean           0.65        0.65      1520.16
## CI.mean           1.27        1.28      2988.60
## var             166.07      169.16 917425865.05
## std.dev          12.89       13.01     30289.04
## coef.var          0.58        0.74         0.27
  * The mean for 'yrs.since.phd' which equals to 22.31, shows that the professors had their PhD for an average of 21 years.
  * std.dev for 'salary' (30289.04) shows the average deviation of individual salaries from the mean salary.
  * The range of 'yrs.since.phd' is 55 (with min=1 & max=56), indicating that the years since earning a Ph.D. range from 1 to 56 years
  * nbr.na for yrs.service = 11, those 11 individuals have been in service for less than a year.

Graphing the distribution

Histogram
hist(mydata$salary,
     probability = FALSE,
     breaks = seq(50000, 250000, 10000),
     main = "Distribution of sample salary",
     xlab = "Salary",
     col = "darkseagreen3",
     border = "black"
     )

##### Explanation of the histogram * This histogram visually represents the distribution of samle salaries, and whether there are any outliers or unusual patterns in the data. * The x-axis represents the salary range, ranging from 50000 to 250000, with intervals of 10000. * The y-axis represents the frequency, meaning the count of individuals falling between each salary range. * Highest observed salary from the sample is 231545 (might be considered as outlier)

Scatter plot
# install.packages("car")
library(car)

scatterplot(y = mydata$salary, 
            x= mydata$yrs.service,
            ylab = "Salary",
            xlab = "Years in service",
            boxplots = FALSE,
            smooth = FALSE,
            groups = mydata$Status,
            col = c("deeppink3", "bisque2", "darkturquoise")
            )

##### Explanation of the scatter plot * The scatter plot above shows the relationship between two variables (years in service and salary) for the groups of professors. * Professors with less years of service tend to have lower salaries (Assistant Professors), while those with more years of experience receive higher salaries (professors). >>> positive correlation

Boxplot
boxplot(mydata$salary)

##### Explanation of the box plot * Shows graphical distribution of the dataset. * The box represents the interquartile range (IQR), ranging from the 25th percentile and the 75th percentile of the data. * The line inside the box is the median, which is the value that separates the lower 50% of the data from the upper 50% (in this case = 107300.00) * The whiskers extend from the edges of the box, showing the range of the data outside the IQR. * The data points above the whisker are the outliers, and they are plotted individually to highlight extreme values that may deviate from the overall patern of the data.

Task 2

Effect of home scooling on body weight in nine graders
2018/2019 —> average weight = 59.5kg
begining of 2021/2022, collected measures from 50 students (n=50)
mydata3 <-read.table("~/Desktop/Bootcamp 2023/R Take Home Exam/Task 2/Body mass.csv",
                     sep = ";",
                     dec = ",",
                     header = TRUE)
head(mydata3)
##   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

Variables: ID: numeric Mass: body weight, numeric

library(pastecs)

as.data.frame(round(stat.desc(mydata3[ , -1]),2),
              optional = TRUE)
##                     
## nbr.val        50.00
## nbr.null        0.00
## nbr.na          0.00
## min            49.70
## max            83.20
## range          33.50
## sum          3143.80
## median         62.80
## mean           62.88
## SE.mean         0.85
## CI.mean.0.95    1.71
## var            36.14
## std.dev         6.01
## coef.var        0.10
  • nbr.null = 0, shows there are no missing values.
  • min & max: the minimum value of body weight gained is 49.70 units, while the maximum is 83.20 units.
  • mean = 62.88, shows the average body weight gained due to online scooling among ninth graders at the beginning of 2021/2022
  • std.dev = 6.01, shows how close are the values to the mean.
Histogram
hist(mydata3$Mass, 
     main = "Distribution of weight gained", 
     xlab = "units of weight gained", 
     ylab = "Frequency", 
     col = "cadetblue3",
     border = "white",
     breaks = seq(from = 20, to = 100, by = 10))

* The shape of the histogram shows a roughly symmetric shape with a peak around the center, meaning that the weight gained due to online scooling is distributed somewhat normally. * As n=50, and n>30, it is less likely to underestimate or overestimate ŷ

Test the following hypothesis with program R: 𝐻0: 𝜇 = 59.5
t.test(mydata3$Mass,
       alternative = "two.sided", 
       mu = 59.5 )
## 
##  One Sample t-test
## 
## data:  mydata3$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

(two-sided test) Assuming a 95% confidence level; alpha=5%

Null hypothesis: H0: 𝜇 = 59.5

Alternative hypothesis: H1: 𝜇 != 59.5

p < 0.001 p < alpha

We reject the null hypothesis at p < 0.001. We can say that there is strong evidence to suggest that the population mean,𝜇, is not equal to 59.5 at a 95% level of confidence.

Effect Size
#install.packages("effectsize")
library(effectsize)

cohens_d(mydata3$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, rule = "sawilowsky2009")
## [1] "medium"
## (Rules: sawilowsky2009)

The effect size (Cohen’s d) of 0.56 (according to the sawilowsky2009 rule) indicates a medium, noticable effect of online schooling on body weight in the examined group of students.

Task 3

Import the dataset Apartments.xlsx

#install.packages("readxl")
library(readxl)

mydata4 <- read_xlsx("/Users/ivanatonevska/Desktop/Bootcamp 2023/R Take Home Exam/Task 3/Apartments.xlsx")
mydata4 <- as.data.frame(mydata4)


tail(mydata4)
##    Age Distance Price Parking Balcony
## 80  38       13  1610       0       0
## 81   9       15  2290       0       1
## 82  14        8  1990       1       0
## 83  18       39  1620       0       0
## 84  22       16  1710       0       1
## 85  32       17  1840       1       0

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
sum(is.na(mydata4))
## [1] 0

There are no missing values in the dataset.

Change categorical variables into factors.

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

mydata4$BalconyF <- factor(mydata4$Balcony,
                           levels = c("0", "1"),
                           labels = c("No", "Yes"))
summary(mydata4[ , -c(4:5)])
##       Age           Distance         Price      ParkingF BalconyF
##  Min.   : 1.00   Min.   : 1.00   Min.   :1400   No :42   No :48  
##  1st Qu.:12.00   1st Qu.: 4.00   1st Qu.:1710   Yes:43   Yes:37  
##  Median :18.00   Median :12.00   Median :1950                    
##  Mean   :18.55   Mean   :14.22   Mean   :2019                    
##  3rd Qu.:24.00   3rd Qu.:20.00   3rd Qu.:2290                    
##  Max.   :45.00   Max.   :45.00   Max.   :2820

Short descriptive statistics summary: * Age 3rd Qu = 24 >>> 75% of the apartments are older than 24 years. * Distance Mean=14.22 >>> The average distance of the apartments from the city center is 14.22km * Price Min & Max >>> The cheapest price per m2 for an apartment is 1400eur, while the most expensive is 2820eur.

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

t.test(mydata4$Price,
       mu = 1900,
       alternative = "two.sided")
## 
##  One Sample t-test
## 
## data:  mydata4$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

H0: Mu_Price = 1900 eur H1: Mu_Price != 1900 eur alpha = 0.05

p-value = 0.0047

p<alpha We can reject H0 at p=0.0047. We found there is significant statistical evidence that the population mean price is not equal to 1900EUR.

mean(mydata4$Price) #sample mean price
## [1] 2018.941

(The sample mean price=2018.94 and the confidence interval suggest the true population mean is higher than 1900EUR)

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 = mydata4)

summary(fit1)
## 
## Call:
## lm(formula = Price ~ Age, data = mydata4)
## 
## 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
Estimate of regression coefficient:

b1=-8.975 If the average age of an apartment increases by 1 year, the price is decreased on average by 8.975eur (p=0.034), assuming all other explanatory variables included in the mode, are constant.

Coefficient of determination:

r2 = 0.05302 0 <= r2 <= 1 The coefficient of determination shows much variability of the dependent variable is explained by the effect of explanatory variable(s).

5.3% of variability of apartments’ price is explained by the linear effect of Age.

Coefficient of correlation:
cor(mydata4$Price, mydata4$Age)
## [1] -0.230255

The correlation coefficient of -0.23 suggest that there is a relatively weak negative relationship between Price and Age of the apartments, meaning that as the age of the apartment increases, its price tends to slightly decrease.

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

library(car)

scatterplotMatrix(mydata4[ , c(3, 1, 2)], #Scatterplot matrix
                  smooth = FALSE,
                  col = "coral2") 

* This scatter plot matrix represents the relationship between multiple variables (price, age and distance). * The boxes above and below the main diagonal show the correlations between the same variables, only oppositely positioned on the x and y axis.

round(cor(as.matrix(mydata4[ , c(3, 1, 2) ])),2)
##          Price   Age Distance
## Price     1.00 -0.23    -0.63
## Age      -0.23  1.00     0.04
## Distance -0.63  0.04     1.00
  • Price-Age (-0.23) >>> weak negative relationship between Price and Age, suggesting that as price increases, the age tends to slightly decrease.
  • Price-Distance (-0.63) >>> semi strong negative correlation between the two variables, indicating that the more expensive the apartment is, the more further away from the city center it is.
  • Age-Distance (0.04) >>> very weak positive correlation, meaning that the variables are not strongly correlated.
cor(mydata4[c("Price", "Age", "Distance")]) 
##               Price         Age    Distance
## Price     1.0000000 -0.23025502 -0.63102794
## Age      -0.2302550  1.00000000  0.04290813
## Distance -0.6310279  0.04290813  1.00000000
# option 2
# Calculating correlation coefficients in order to assess multicollinearity.

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

fit2 <- lm(Price ~ Age + Distance,
           data = mydata4)
summary(fit2)
## 
## Call:
## lm(formula = Price ~ Age + Distance, data = mydata4)
## 
## 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.

#install.packages("car")
library(car)

vif(fit2)
##      Age Distance 
## 1.001845 1.001845
mean(vif(fit2))
## [1] 1.001845

As the VIF values are lower than 5 (and the mean value of 1.002) we can say that there is no correlation between the two explanatory variables Age and Distance, so we do not have to remove any of them for the following analysis. (The requirement for multicolinearity was not violated)

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

mydata4$StdResid <- round(rstandard(fit2), 3) #Standardized residuals

mydata4$CooksD <- round(cooks.distance(fit2), 3) #Cooks distances
plot(mydata4$CooksD, mydata4$StdResid,
     xlab = "Cooks Distances",
     ylab = "Standardized residuals",
     main = "Scatterplot of Cook's Dist. vs Std.resid.")

head(mydata4[order(mydata4$StdResid),], 3) #Three units with lowest value of stand. residuals
##    Age Distance Price Parking Balcony ParkingF BalconyF StdResid
## 53   7        2  1760       0       1       No      Yes   -2.152
## 13  12       14  1650       0       1       No      Yes   -1.499
## 72  12       14  1650       0       0       No       No   -1.499
##    CooksD
## 53  0.066
## 13  0.013
## 72  0.013
head(mydata4[order(-mydata4$CooksD),], 5) #Five units with highest value of Cooks distance
##    Age Distance Price Parking Balcony ParkingF BalconyF StdResid
## 38   5       45  2180       1       1      Yes      Yes    2.577
## 55  43       37  1740       0       0       No       No    1.445
## 33   2       11  2790       1       0      Yes       No    2.051
## 53   7        2  1760       0       1       No      Yes   -2.152
## 22  37        3  2540       1       1      Yes      Yes    1.576
##    CooksD
## 38  0.320
## 55  0.104
## 33  0.069
## 53  0.066
## 22  0.061
  • Since the apartment with ID 38 has a relatively higher Cook’s Distance value compared to the others, it can be considered a highly influential unit and should be removed.
which.max(mydata4$CooksD)
## [1] 38
maxCooks <- which.max(mydata4$CooksD) #Influential unit

mydata4 <- mydata4[-maxCooks, ] #Removing the influential unit
fit2 <- lm(Price ~ Age + Distance, data = mydata4) #re-fitting the linear regression model after removing the influential unit

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

mydata4$StdResid <- scale(residuals(fit2))
mydata4$StdFitted <- scale(fitted.values(fit2)) 

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

#install.packages("olsrr")
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          =    2.927455 
##  Prob > Chi2   =    0.08708469

H0: the variance is constant
H1: the variance is not constant ##### P value is approx. 0.087, (p>alpha 0.05) and we do not have strong evidence to reject the null hypothesis.

#Scatter plot with ggplot function 
library(ggplot2)

ggplot(mydata4, aes(y = StdResid, x = StdFitted )) +
  geom_point() +
  ylab("Standardized residuals") +
  xlab("Standardized fitted values")

#Results of regression model
summary(fit2) 
## 
## Call:
## lm(formula = Price ~ Age + Distance, data = mydata4)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -604.92 -229.63  -56.49  192.97  599.35 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2456.076     73.931  33.221  < 2e-16 ***
## Age           -6.464      3.159  -2.046    0.044 *  
## Distance     -22.955      2.786  -8.240 2.52e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 276.1 on 81 degrees of freedom
## Multiple R-squared:  0.4838, Adjusted R-squared:  0.4711 
## F-statistic: 37.96 on 2 and 81 DF,  p-value: 2.339e-12

AGE H0: Beta1 = 0 H1: Beta1 !=0c p =0.044

Explanation of b1 = -6.464 If average age of apartments is increased by 1 year, price is decrease on average by 6.464 units, assuming that all other explanatory variables, included in the model, are constant.

DISTANCE H0: Beta2 = 0 H1: Beta2 != 0 p < 0.001

Explanation of b2 = -22.955 If apartment’s distance from city center increases by 1km, then the price on average decreases by 22.955 units (p < 0.001), assuming that all other explanatory variables included in the mode, are constant.

Multiple-R2: 0.4838 48.38% of variability of price can be explained by the linear effect of Age and Distance

Test of significance of regression H0: Ro2 = 0 H1: Ro2 > 0 p<0.001 The f-test has a very low p value which indicates that Age and Distance are statistically significant and we can reject the H0, concluding that there is linear relationship between Price and the included explanatory variables.

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

shapiro.test(mydata4$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata4$StdResid
## W = 0.9574, p-value = 0.007233

H0: Variable IS normally distributed H1: Variable is NOT normally distributed

p=0.0072 >>>> we reject H0 (at p<0.001) >>>> we say that standardized residuals are not normally distributed. (they deviate from the normal distribution)

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

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

summary(fit2)
## 
## Call:
## lm(formula = Price ~ Age + Distance, data = mydata4)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -604.92 -229.63  -56.49  192.97  599.35 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2456.076     73.931  33.221  < 2e-16 ***
## Age           -6.464      3.159  -2.046    0.044 *  
## Distance     -22.955      2.786  -8.240 2.52e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 276.1 on 81 degrees of freedom
## Multiple R-squared:  0.4838, Adjusted R-squared:  0.4711 
## F-statistic: 37.96 on 2 and 81 DF,  p-value: 2.339e-12

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 + as.factor(Parking) + as.factor(Balcony), data = mydata4)


summary(fit3)
## 
## Call:
## lm(formula = Price ~ Age + Distance + as.factor(Parking) + as.factor(Balcony), 
##     data = mydata4)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -473.21 -192.37  -28.89  204.17  558.77 
## 
## Coefficients:
##                     Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         2329.724     93.066  25.033  < 2e-16 ***
## Age                   -5.821      3.074  -1.894  0.06190 .  
## Distance             -20.279      2.886  -7.026 6.66e-10 ***
## as.factor(Parking)1  167.531     62.864   2.665  0.00933 ** 
## as.factor(Balcony)1  -15.207     59.201  -0.257  0.79795    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 267.5 on 79 degrees of freedom
## Multiple R-squared:  0.5275, Adjusted R-squared:  0.5035 
## F-statistic: 22.04 on 4 and 79 DF,  p-value: 3.018e-12

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 + as.factor(Parking) + as.factor(Balcony)
##   Res.Df     RSS Df Sum of Sq      F  Pr(>F)  
## 1     81 6176767                              
## 2     79 5654480  2    522287 3.6485 0.03051 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Model 2 is better than Model 1, as p=0.03051. This shows that adding categorical predictors, like Parking and Balcony, would significantly improve the model’s fit, explaining more of the variation in Price compared to Model 1.

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 + as.factor(Parking) + as.factor(Balcony), 
##     data = mydata4)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -473.21 -192.37  -28.89  204.17  558.77 
## 
## Coefficients:
##                     Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         2329.724     93.066  25.033  < 2e-16 ***
## Age                   -5.821      3.074  -1.894  0.06190 .  
## Distance             -20.279      2.886  -7.026 6.66e-10 ***
## as.factor(Parking)1  167.531     62.864   2.665  0.00933 ** 
## as.factor(Balcony)1  -15.207     59.201  -0.257  0.79795    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 267.5 on 79 degrees of freedom
## Multiple R-squared:  0.5275, Adjusted R-squared:  0.5035 
## F-statistic: 22.04 on 4 and 79 DF,  p-value: 3.018e-12
  • The coefficient for Parking is statistically significant (p = 0.00933), suggesting that the presence of Parking 1 has a statistically significant effect on Price. It is associated with an estimated increase of 167.531 units in Price compared to the reference category.

  • The coefficient for Balcony is not statistically significant (p = 0.79795), suggesting that the presence of Balcony 1 does not have a statistically significant effect on Price. There is no strong evidence to suggest that the presence of Balcony affects the Price.

H0: all reg.coeff. = 0 H1: all reg.coeff. != 0

Save fitted values and claculate the residual for apartment ID2.

fitted_values <- predict(fit3, newdata = mydata4)
row_id <- which(mydata4$ApartmentID == 2)
residual_apartment2 <- mydata4$Price[row_id] - fitted_values[row_id]


residual_apartment2
## numeric(0)