R-Exam

Zoja CIGLENECKI

Excercise 1 - Survey of Labour and Income Dynamics

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

 mydata <- force(SLID)
 
 head(mydata)
##   wages education age    sex language
## 1 10.56      15.0  40   Male  English
## 2 11.00      13.2  19   Male  English
## 3    NA      16.0  49   Male    Other
## 4 17.76      14.0  46   Male    Other
## 5    NA       8.0  71   Male  English
## 6 14.00      16.0  50 Female  English

Explanation of dataset:

  • Wage: Composite hourly wage rate from all jobs.

  • Education: Number of years of schooling.

  • Age: in years.

  • Sex: A factor with leves: Female, Male

  • Language: A factor with levels: English, French, Other.

#install.packages("tidyr")
library(tidyr)
mydata2 <- drop_na(mydata)
mydata2$sex <- factor(mydata2$sex, 
                          levels = c("Male", "Female"),
                          labels = c("M", "F"))

mydata2$language <- factor(mydata2$language, 
                          levels = c("English", "French","Other"),
                          labels = c("EN", "FR","OR"))
mydataF <- mydata2[mydata2$sex == "F" , ]

mydataM <-mydata2[mydata2$sex == "M" , ]
summary(mydata2)
##      wages         education          age       sex      language 
##  Min.   : 2.30   Min.   : 0.00   Min.   :16.0   M:1986   EN:3244  
##  1st Qu.: 9.25   1st Qu.:12.00   1st Qu.:28.0   F:2001   FR: 259  
##  Median :14.13   Median :13.00   Median :36.0            OR: 484  
##  Mean   :15.54   Mean   :13.34   Mean   :37.1                     
##  3rd Qu.:19.72   3rd Qu.:15.10   3rd Qu.:46.0                     
##  Max.   :49.92   Max.   :20.00   Max.   :69.0

The average hourly wage is 15.54.

People in the survey had a maximum of 20 years of education.

The survey included 75 % of people younger or of the age 46, and 25 % older than 46. They were from 16 to 69 years old.

library(psych)
describeBy(mydata2, mydata2$sex)
## 
##  Descriptive statistics by group 
## group: M
##           vars    n  mean    sd median trimmed   mad min   max range  skew kurtosis   se
## wages        1 1986 17.24  8.21   16.2   16.49  8.08   3 49.44 46.44  0.87     0.80 0.18
## education    2 1986 13.26  3.16   13.0   13.23  2.97   0 20.00 20.00 -0.04     0.39 0.07
## age          3 1986 37.26 12.18   36.0   36.85 13.34  16 69.00 53.00  0.27    -0.74 0.27
## sex*         4 1986  1.00  0.00    1.0    1.00  0.00   1  1.00  0.00   NaN      NaN 0.00
## language*    5 1986  1.31  0.67    1.0    1.14  0.00   1  3.00  2.00  1.89     1.86 0.02
## --------------------------------------------------------------------------- 
## group: F
##           vars    n  mean    sd median trimmed   mad  min   max range  skew kurtosis   se
## wages        1 2001 13.85  7.12  12.29   12.86  6.67  2.3 49.92 47.62  1.28     1.82 0.16
## education    2 2001 13.41  2.92  13.00   13.40  2.97  0.0 20.00 20.00 -0.29     1.63 0.07
## age          3 2001 36.94 12.09  36.00   36.53 13.34 16.0 69.00 53.00  0.26    -0.76 0.27
## sex*         4 2001  2.00  0.00   2.00    2.00  0.00  2.0  2.00  0.00   NaN      NaN 0.00
## language*    5 2001  1.31  0.68   1.00    1.13  0.00  1.0  3.00  2.00  1.92     1.93 0.02

Males have on average a higher hourly rate (mean=17.24) than females (mean=13.85) with less years of education on average.

M: education mean=13.26

F: education mean=13.41

library(car)
## 
## Attaching package: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
scatterplotMatrix(mydata[ , c(-4, -5)], 
                  smooth = FALSE) 

Wages are positively distributed to the right, with one higher and one lower mode. Education is normally distributed with one peak near arithmetic mean. Age is also normally distributed, probably given that most people who work are middle aged - one mode.

Excercise 2 - Body mass

mydatatask2<-read.table("./Body mass.csv",header= TRUE,sep=";", dec=",")

head(mydatatask2)
##   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

Explanation:

  • ID: ID of the student.

  • Mass: Body mass of one student.

hist(mydatatask2$Mass, 
     main = "Distribution Body mass 2021/2022", 
     xlab = "Mass", 
     ylab = "Frequency")

mean(mydatatask2$Mass)
## [1] 62.876
sd(mydatatask2$Mass)
## [1] 6.011403

Hypothesis testing

We are testing if the body mass has changed from 2018/2019 to 2021/2022.

  • H0: mu = 59.5

  • H1: mu!= 59.5 “two sided test”

t.test(mydatatask2$Mass,
       mu=59.5,
       alternative="two.sided")
## 
##  One Sample t-test
## 
## data:  mydatatask2$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
  • Explanation of the result 1: We reject H0 at p<0.001 and except H1.

    Average mass in the year 2021/2022 is different from the one in 2018/2019. It increased to 62.876.

  • Explanation of the result 2: 95% CI for arithemtic mean: 61.16758 < Mu < 64.58442

    Because 59.9 is not included in the interval we reject H0 at 5%.

Effect size

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

There is a medium difference between body mass in ninth graders between 2018/2019 and 2021/2022.

Excercise 3

Import the dataset Apartments.xlsx

library(readxl)

mydatatask3<- read_xlsx("./Apartments.xlsx")

mydata3 <- as.data.frame(mydatatask3)

head(mydata3)
##   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.

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


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

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

#H0: Mu price= 1900 eur
#H1: Mu price !=1900 eur


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

We can reject H0 at p=0.0048 and except H1.

Average price of the apartment is not equal to 1900 eur. The average price is 2018.941 eur.

95% CI for arithemtic mean: 1937.443< Mu < 2100.440

Because 1900 is not included in the interval we reject H0 at 5%.

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

summary(fit1)
## 
## Call:
## lm(formula = Price ~ Age, data = mydata3)
## 
## 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

yˆ(Price)= 2185.46 - 8.98 (Age) b0= 2185.46 -> Expected price of a mˆ2 of a new apartment (Age=0)

If the age of an apartment increases by one year, the price of an apartment mˆ2 decreases by 8.98 eur on average.

Coefficient of determination: Rˆ2 = 0.05302, 5.3% of variability of price can be explained by the effect of age.

cor(mydata3$Price, mydata3$Age)
## [1] -0.230255

R= -0.23 Pearson Correlation Coefficient: There is a negative weak linear relationship between price and age.

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

scatterplotMatrix(mydata3[ , c(-4, -5)], 
                  smooth = FALSE) 

There is no potential multi-colinearity between the variables based on the matrix.

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

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

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

Chech the multicolinearity with VIF statistics. Explain the findings.

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

Based on VIF statistics neither of the variables needs to be removed, because VIF<5.

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

mydata3$StdResid <- (rstandard(fit2))
                         
mydata3$CooksD <- (cooks.distance(fit2))
shapiro.test(mydata3$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata3$StdResid
## W = 0.95306, p-value = 0.00366
  • H0: Variable is normally distributed

  • H1: Variable is not normally distr.

We reject H0 at p=0.003 and except H1.

hist(mydata3$CooksD, 
     xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histogram of Cooks distances") #One high influence unit

head(mydata3[order(-mydata3$StdResid),], 3)
##    Age Distance Price Parking Balcony StdResid     CooksD
## 38   5       45  2180     Yes     Yes 2.576772 0.31973058
## 33   2       11  2790     Yes      No 2.050586 0.06913379
## 2   18        1  2800     Yes      No 1.783288 0.03036543
head(mydata3[order(-mydata3$CooksD),], 6)
##    Age Distance Price Parking Balcony  StdResid     CooksD
## 38   5       45  2180     Yes     Yes  2.576772 0.31973058
## 55  43       37  1740      No      No  1.444768 0.10420445
## 33   2       11  2790     Yes      No  2.050586 0.06913379
## 53   7        2  1760      No     Yes -2.151787 0.06625775
## 22  37        3  2540     Yes     Yes  1.575982 0.06086868
## 39  40        2  2400      No     Yes  1.091176 0.03750987
#mydata3 <- mydata3[-38, ] #Removing ID60 due to highest CooksD, even though it is lower than 1, it also has the highest StdResid value 

head(mydata3[order(-mydata3$CooksD),], 6)
##    Age Distance Price Parking Balcony  StdResid     CooksD
## 38   5       45  2180     Yes     Yes  2.576772 0.31973058
## 55  43       37  1740      No      No  1.444768 0.10420445
## 33   2       11  2790     Yes      No  2.050586 0.06913379
## 53   7        2  1760      No     Yes -2.151787 0.06625775
## 22  37        3  2540     Yes     Yes  1.575982 0.06086868
## 39  40        2  2400      No     Yes  1.091176 0.03750987
fit2 <- lm(Price ~ Age+Distance,
           data = mydata3) 

#Running the function again due to removing one value

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

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

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

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          =    0.968106 
##  Prob > Chi2   =    0.325153
  • H0: Homoskedasticity

  • H1: Heteroskedasticity

p=0.087: We can not reject H0. The variance is constant, meaning the graph is homoskedastic.

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

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

shapiro.test(mydata3$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata3$StdResid
## W = 0.95306, p-value = 0.00366
  • H0: Std. residuals are normally distributed

  • H1: Std. residuals are not normally distr.

  • We reject H0 at p=0.002 and except H1. Standardized residuals are not normally distributed.

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

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

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

Due to homoskedasticity we can trust the results. Both age and distance have a statistical effect on price, because p<0.05.

  • Age: H0: Beta1=0 H1: Beta1!=0 p=0.016

Explanation of b1= -7.934

If the age of an apartment increases by 1 year, than the average price of an apartment mˆ2 decreases by 7.943 eur, at p=0.016, assuming all other explanatory variables in the model are constant.

  • Distance: H0: Beta2=0 H1: Beta2!=0 p<0.001

Explanation of b2= -20.667

If the distance of an apartment from the city center increases by 1km, than the average price of an apartment mˆ2 decreases on average by 20.667 eur, assuming all other explanatory variables in the model are constant.

  • Multiple R2: 0.4396 43.96% of variability of price of a mˆ2 of an apartment is explained by linear effect of Age and Distance.

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+Parking+Balcony,
           data = mydata3) 

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 + Parking + Balcony
##   Res.Df     RSS Df Sum of Sq      F  Pr(>F)  
## 1     82 6720983                              
## 2     80 5991088  2    729894 4.8732 0.01007 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
  • H0: Model 1 (Fit 1) is better.
  • H1: Model 2 (Fit 2) is better.

p=0.01

We can reject H0 at p=0.01.

Meaning model 2 is better, it explains more variability in price of a mˆ2 of an apartment.

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 + Parking + Balcony, data = mydata3)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -459.92 -200.66  -57.48  260.08  594.37 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2301.667     94.271  24.415  < 2e-16 ***
## Age           -6.799      3.110  -2.186  0.03172 *  
## Distance     -18.045      2.758  -6.543 5.28e-09 ***
## ParkingYes   196.168     62.868   3.120  0.00251 ** 
## BalconyYes     1.935     60.014   0.032  0.97436    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 273.7 on 80 degrees of freedom
## Multiple R-squared:  0.5004, Adjusted R-squared:  0.4754 
## F-statistic: 20.03 on 4 and 80 DF,  p-value: 1.849e-11
  • H0: Beta3=0
  • H1: Beta3!=0 p=0.003

b3=196.168

Assuming that all other variables are the same, the apartments that come with a parking have on average a higher price by 196 eur per mˆ2, compared to the apartments with no parking, at p=0.003.

  • H0: Beta4=0
  • H1: Beta4!=0 p=0.975

b4=1.935

Balcony is not significant, because p=0.975.

However assuming all other variables are the same, the apartments that have balconies have on average a higher price by 2 eur per mˆ2, compared to the apartments with no parking, at p=0.975.

  • Rˆ2= 0.5004 R square increased to 0.5004, meaning that 50.04% of the variability of price of a mˆ2 of an apartment is can be explained by linear effect of age, distance and if they include a parking and balcony.

  • F-statistics -> Test of significance of regression H0: Roˆ2 =0 H1: Ro > 0 F=20.03, P<0.001

We reject null hypothesis at p<0.001, we can say that population coefficient of determination is more than 0, meaning that we found linear relationship between price of a mˆ2 of an apartment and explanatory variables, included in the model.

Save fitted values and claculate the residual for apartment ID2.

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

head(mydata3[colnames(mydata3) %in% c("Price", "Fitted", "Residuals")]) 
##   Price   Fitted  Residuals
## 1  1640 1750.741 -110.74150
## 2  2800 2357.411  442.58893
## 3  1660 1748.807  -88.80674
## 4  1850 1589.921  260.07897
## 5  1640 2052.576 -412.57579
## 6  1770 1896.691 -126.69107
#e (residual)=Y-Y(fitted)
  • ID2: Residual is 442.6 eur.