Maja Železnikar Home Exam

Task 1

data(package = .packages(all.available = TRUE))
#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

1.1. Explanation of the data set

The data set represents information collected from individuals in the 1994 wave of the Canadian Survey of Labour and Income Dynamics (SLID) in the province of Ontario.

  • Wages: Composite hourly wage rate from all jobs
  • Education: Number of years of schooling
  • Age: Age in years
  • Sex: Female or Male
  • Language: English, French or Other

1.2. Performing data manipulations

Removing the NAs
library(tidyr)
mydata2 <- drop_na(mydata)
Renaming columns
colnames(mydata2)[colnames(mydata2) == "wages"] <- "Hourly wage rate"
colnames(mydata2)[colnames(mydata2) == "education"] <- "Education"
colnames(mydata2)[colnames(mydata2) == "age"] <- "Age"
colnames(mydata2)[colnames(mydata2) == "sex"] <- "Gender"
colnames(mydata2)[colnames(mydata2) == "language"] <- "Language"
Creating a new data frame:
mydata3 <- mydata2[mydata2$Language == "English", ] # Data frame which includes only English speaking people

1.3. Present descriptive statistics with min. 3 sample statistics

library(pastecs)
## 
## Attaching package: 'pastecs'
## The following object is masked from 'package:tidyr':
## 
##     extract
summary(mydata2)
##  Hourly wage rate   Education          Age          Gender        Language   
##  Min.   : 2.30    Min.   : 0.00   Min.   :16.0   Female:2001   English:3244  
##  1st Qu.: 9.25    1st Qu.:12.00   1st Qu.:28.0   Male  :1986   French : 259  
##  Median :14.13    Median :13.00   Median :36.0                 Other  : 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

Wages:

Median = 14.13 <- 50% of people has 14.13 composite hourly wage rate and 50% has more than that. Max = 49.92 <- Maximum composite hourly wage rate is 49.92.

Education :

Mean = 13.00 <- Average number of years of schooling is 13.34. 3rd Qu = 15.10 <- 75% of people has 15.10 years of schooling or less, 25% has more.

Age:

Min = 16.00 <- The youngest person in the sample is 16 years old.

I would like to know the percentages of languages spoken:
language_counts <- table(mydata2$Language) #Counting occurrences of each language

language_percentages <- (language_counts / sum(language_counts)) * 100 #Calculating percentages


language_summary <- data.frame(        #Creating a data frame to display the results        
  Language = names(language_counts),
  Count = as.numeric(language_counts),
  Percentage = language_percentages)

print(language_summary) #Printing the summary
##   Language Count Percentage.Var1 Percentage.Freq
## 1  English  3244         English       81.364434
## 2   French   259          French        6.496112
## 3    Other   484           Other       12.139453
language_summary$Percentage <- round(language_summary$Percentage.Freq, 2) 
#Creating new column to round percentages

Results: 81.36% of people speak English, 12.14% speak other languages and only 6.5% speak French.

1.4. Graph

hist(mydata2$`Hourly wage rate`,
     xlab = "Hourly wage rate",
     ylab = "Frequency",
     main = "Histogram of Hourly wage rates",
     breaks = seq(from = 0, to = 50, by = 5),
     col = "pink1")

Histogram of Composite hourly wage rates shows that the distribution of Composite hourly wage rate is assimetrical to the right. Most frequent composite hourly wage rate is around 10.

hist(mydata2$Age,
     xlab = "Age",
     ylab = "Frequency",
     main = "Histogram of Age",
     breaks = seq(from = 0, to = 70, by = 5),
     col = "violet")

Variable Age is distributed normally, most frequent age is around 35 years.

boxplot(mydata2$Education,
        col = c("lightblue1"), 
        main = "Boxplot of Education",
        ylab = ("Years of schooling"),
        outcol = "darkblue")

Based on the boxplot we can see that distribution of years of schooling is asimetrical to the left. Interquartile range is somewhere between 12 and 15 years, the Median is around 13 years. Boxplot also shows that there are many outliers, which mostly have less years of schooling than the others.

Task 2

mydata <- read.csv("./Body mass.csv", header = TRUE, sep = ";", dec = ",")
head(mydata)
##   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

2.1 Descriptive statistics and histogram

Descriptive statistics
library(psych)
round(stat.desc(mydata$Mass), 2)
##      nbr.val     nbr.null       nbr.na          min          max        range          sum       median 
##        50.00         0.00         0.00        49.70        83.20        33.50      3143.80        62.80 
##         mean      SE.mean CI.mean.0.95          var      std.dev     coef.var 
##        62.88         0.85         1.71        36.14         6.01         0.10
Histogram
hist(mydata$Mass,
     main = "Histogram of body mass",
     col = "lightblue",
     xlab = "Body Mass", 
     ylab = "Frequency",
     breaks = seq(from = 40, to = 90, by = 5))

2.2. Hypothesis testing

H0: Mu = 59.5

H1: Mu =/ 59.5 two sided

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

2.3.Result explanation and interpreting effect size

Results

Estimation of arithmetic mean of body mass in 2021/2022: y_hat = 62.876 p-value is 0.000234 (extremely low (0.001)) <- how likely it is that Mu is 59.5

We reject H0 at p < 0.001 and accept H1. Average weight (body mass) in the school year 2021/2022 is different than it was in 2018/2019. The weight increased.

95% confidence interval for arithmetic mean : 62 < Mu < 65 Because 59.5 is not included in the interval, we reject H0.

Effect Size
library(effectsize)
## 
## Attaching package: 'effectsize'
## The following object is masked from 'package:psych':
## 
##     phi
cohens_d(mydata$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)

The size of the effect based on Cohen’s d is 0.56, which is medium effect based on Sawilowsky rule.

Task 3

Import the dataset Apartments.xlsx

library(readxl)
mydata <- read_xlsx("./Apartments.xlsx")
mydata <- as.data.frame(mydata) 
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.

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

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

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

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

H1: Mu =/ 1900

We reject H0 at (p>0.005) and accept H1. We assume that average price of the apartment is different than 1900.

At 95% confidence interval for arithmetic mean, Mu -> 1937 < Mu < 2100

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

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

Regression function: Price = 2185.455 - 8.975 * Age

b0 = 2185.455

Regression coefficient:

b1 = - 8.975 -> If Age of an apartment increases by 1 year, Price per m2 on average decreases by 8.975.

Coefficient of determination:

R2 = 0.05302 -> 5,3% of variability of Price can be explained by the effect of age of the apartment.

Coefficient of correlation:
round(cor(mydata$Price, mydata$Age), 3)
## [1] -0.23

r = -0.23 There is negative weak linear correlation between Price and Age of the apartment.

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

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

Based on the matrix, there is no potential problem with multicollinearity, because points on scatterplots are not too closely clustered together and they are not forming a linear pattern.

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

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

summary(fit2)
## 
## Call:
## lm(formula = Price ~ Age + Distance, data = mydata)
## 
## 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
mean(vif(fit2))
## [1] 1.001845

Since both values are below 5, multicollinearity is not a problem. This means that Age and Distance are not too correlated. Also, the mean of both values is almost 1, which is a great sign (no multicollinearity).

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

mydata$StdResid <- round(rstandard(fit2), 3) 
mydata$CooksD <- round(cooks.distance(fit2), 3)

# Checking the histograms to see the distributions
hist(mydata$StdResid,
     col ="lightgreen",
     xlab = "Standardized Residuals", 
     ylab = "Frequency", 
     main = "Histogram of Standardized Residuals")

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

All standard residuals are within -3 to 3, so there are no potential outliers and we do not have to remove any units.

Cooks Distances are all below 1, but there is one unit that is very distant from all the others (potential unit with high influence), so it has to be removed.
This unit is number 38 and has Cooks Distance 0.32 and Standardized Residual 2.577.

head(mydata[order(-mydata$CooksD),], 6) # I ordered CooksD in descending order to find unit with highest value => unit 38
##    Age Distance Price Parking Balcony ParkingF BalconyF StdResid CooksD
## 38   5       45  2180       1       1      Yes      Yes    2.577  0.320
## 55  43       37  1740       0       0       No       No    1.445  0.104
## 33   2       11  2790       1       0      Yes       No    2.051  0.069
## 53   7        2  1760       0       1       No      Yes   -2.152  0.066
## 22  37        3  2540       1       1      Yes      Yes    1.576  0.061
## 39  40        2  2400       0       1       No      Yes    1.091  0.038
Removing the unit:
mydata <- mydata[-38, ] #Removing unit ID38

# Assigning model fit2 again
fit2 <- lm(Price ~ Age + Distance, 
          data = mydata)

# Assignings Std. Residuals and Cook's D. again
mydata$StdResid <- round(rstandard(fit2), 3) 
mydata$CooksD <- round(cooks.distance(fit2), 3)

# Checking distributions after removing the unit
hist(mydata$CooksD,              
     xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histogram of Cooks distances",
     col = "orange")

hist(mydata$StdResid,
     col ="lightgreen",
     xlab = "Standardized Residuals", 
     ylab = "Frequency", 
     main = "Histogram of Standardized Residuals")

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

fit2 <- lm(Price ~ Age + Distance,
          data = mydata)
mydata$StdFitted <- scale(fit2$fitted.values)

library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
ggplot(mydata, aes(y = StdResid, x = StdFitted)) +
  geom_point() +
  ylab("Standardized residuals") + 
  xlab("Standardized Fitted values") + 
  stat_smooth(method = "lm", formula = y ~ x, se = F) + 
  theme_bw()

Based on the scatterplot, there is no heteroskedasticity, spread of Std. Residuals does not widen or narrow

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

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

# We check this with Shapiro-Wilk normality test
shapiro.test(mydata$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata$StdResid
## W = 0.95649, p-value = 0.006355

H0: Variable is normally distributed

H1: Variable is NOT normally distributed

We cannot reject H0, because p > 0.005. We cannot say that standardized residuals are not distributed normally so we assume that they are normally distributed.

But we have a large sample (more than 30 units) so we do not have to worry that much about that.

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 = mydata)
## 
## 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
Partial regression coefficients:

H0: Beta1 = 0

H1: Beta1 =/ 0

p = 0.044

b1 =-6.464 <- If Age of the apartment increases by 1 year, Price of the apartment decreases on average by 6.464 eur (p < 0.005), assuming all the other explanatory variables included in the model are constant.

H0: Beta2 = 0

H1: Beta2 =/ 0

p = 2.52e-12

b2 = -22.955

If Distance from the apartment to the center increases by 1 km, Price of the apartment decreases on average by 22.955 eur (p < 0.001), assuming all the other explanatory variables included in the model are constant.

Coefficient of determination:

R2 = 0.4838

48.38 % of variability of Price can be explained by the linear effects 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 + ParkingF + BalconyF,       
          data = mydata)    

# I included factorized variables, R automatically sets 0 and 1 as values of each factor

summary(fit3)
## 
## Call:
## lm(formula = Price ~ Age + Distance + ParkingF + BalconyF, data = mydata)
## 
## 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 ***
## ParkingFYes  167.531     62.864   2.665  0.00933 ** 
## BalconyFYes  -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 + ParkingF + BalconyF
##   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

H0: Model fit2 is better.

H1: Model fit3 is better.

p = 0.03051

We reject H0 at p < 0.05. Model fit3 is better, because it explains more variability in Price. R2 is also higher.

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 + ParkingF + BalconyF, data = mydata)
## 
## 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 ***
## ParkingFYes  167.531     62.864   2.665  0.00933 ** 
## BalconyFYes  -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
Regression coefficients

H0: Beta3 = 0

H1: Beta3 =/ 0

p < 0.05

Explaining b3 = 167.531

Assuming that all other variables are the same, the apartment with parking has on average by 167.531 eur higher price compared to apartments without the parking at p < 0.05.

H0: Beta4 = 0

H1: Beta4 =/ 0

p > 0.05

We do not explain statistically unimportant coefficients.

We cannot say that Balcony has statistical effect on Price (p-value is too high).

F- Statistics

H0: Ro2 = 0

H1: Ro2 =/0

F = 22.04

p = 3.018e-12 (p < 0.001)

We reject H0 at p < 0.001. We can say that population coefficient of determination is more than 0 meaning that we found linear relationship between Price and explanatory variables included in the model.

Save fitted values and calculate the residual for apartment ID2.

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


mydata$Residuals[2]  # Residual of apartment ID2
## [1] 427.8029