Bogdan Perić 19568506

HOMEWORK 2

Part 1

Importing data set found online at https://www.kaggle.com/datasets/gabrielluizone/high-school-alcoholism-and-academic-performance.

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

Showing first 2 rows of data set.

head(mydata, 2)
##            School Gender Age Housing_Type Family_Size Parental_Status
## 1 Gabriel Pereira Female  18        Urban     Above 3       Separated
## 2 Gabriel Pereira Female  17        Urban     Above 3 Living Together
##   Mother_Education Father_Education Mother_Work Father_Work
## 1 Higher Education Higher Education   Homemaker     Teacher
## 2   Primary School   Primary School   Homemaker       other
##   Reason_School_Choice Legal_Responsibility Commute_Time Weekly_Study_Time
## 1    Course Preference               Mother 15 to 30 min           2 to 5h
## 2    Course Preference               Father Up to 15 min           2 to 5h
##   Extra_Educational_Support Parental_Educational_Support Private_Tutoring
## 1                       Yes                           No               No
## 2                        No                          Yes               No
##   Extracurricular_Activities Attended_Daycare Desire_Graduate_Education
## 1                         No              Yes                       Yes
## 2                         No               No                       Yes
##   Has_Internet Is_Dating Good_Family_Relationship Free_Time_After_School
## 1           No        No                     Good               Moderate
## 2          Yes        No                Excellent               Moderate
##   Time_with_Friends Alcohol_Weekdays Alcohol_Weekends Health_Status
## 1              High         Very Low         Very Low          Fair
## 2          Moderate         Very Low         Very Low          Fair
##   School_Absence Grade_1st_Semester Grade_2nd_Semester
## 1              4                  0                 11
## 2              2                  9                 11

Research question: Is there association between gender and extracurricular activities? As it can be seen above, data set is rather complex and it includes numerous variables. For the purpose of simplifying, the new object was created and it contains only 2 variables: gender and extracurricular activities.

mydata1 <- mydata[, c("Gender", "Extracurricular_Activities")]

Turning categorical variables into factors and showing first 3 rows of data in new object. Factoring was not done in exact same manner as during lectures because this data set already included labels Male, Female, Yes and No, so there was no need to turn levels into factors. Thus, the aim of this step was just to turn character to factor.

mydata1$Gender <- factor(mydata1$Gender)
mydata1$Extracurricular_Activities <- factor(mydata1$Extracurricular_Activities)
head(mydata1,3)
##   Gender Extracurricular_Activities
## 1 Female                         No
## 2 Female                         No
## 3 Female                         No

Descriptive statistic of data set (it does not tells us a lot, since both variables are categorical).

library(psych)
## Warning: package 'psych' was built under R version 4.3.2
describe(mydata1)
##                             vars   n mean   sd median trimmed mad min max range
## Gender*                        1 649 1.41 0.49      1    1.39   0   1   2     1
## Extracurricular_Activities*    2 649 1.49 0.50      1    1.48   0   1   2     1
##                             skew kurtosis   se
## Gender*                     0.37    -1.87 0.02
## Extracurricular_Activities* 0.06    -2.00 0.02

Quick summary of whole data set by categories.

summary(mydata1)
##     Gender    Extracurricular_Activities
##  Female:383   No :334                   
##  Male  :266   Yes:315

Since variables are categorical, we need to use Pearson’s Chi square test. In this case it is with Yates’ continuity correction, because table is 2x2. The goal of this test is to examine if association between gender and extracurricular activities exist. We can reject null hypothesis at p-value = 0.002, which proves that association between two variable indeed exists. Results of the test are presented below.

results <- chisq.test(mydata1$Gender, mydata1$Extracurricular_Activities, correct = TRUE)
results
## 
##  Pearson's Chi-squared test with Yates' continuity correction
## 
## data:  mydata1$Gender and mydata1$Extracurricular_Activities
## X-squared = 9.5922, df = 1, p-value = 0.001954

Here we have the sums of all observed or empirical frequencies.

addmargins(results$observed)
##               
## mydata1$Gender  No Yes Sum
##         Female 217 166 383
##         Male   117 149 266
##         Sum    334 315 649

Here we have expected frequencies rounded at 2 decimals. If, for example, there would be no association between 2 variables we would expect to see that 197 females did not participate in any extracurricular activity.

round(results$expected, 2)
##               
## mydata1$Gender     No    Yes
##         Female 197.11 185.89
##         Male   136.89 129.11

Here we have standardized residuals rounded to 2 decimals. There is more than expected females that did not participate in any extracurricular activities, while there is less than expected males that participated.

round(results$residuals, 2)
##               
## mydata1$Gender    No   Yes
##         Female  1.42 -1.46
##         Male   -1.70  1.75

Following steps are about the analysis of structures.Table below shows proportions of categories rounded to 3 decimals. That being said Female/No can be obtained as 217/649 = 0.334.

addmargins(round(prop.table(results$observed), 3))
##               
## mydata1$Gender    No   Yes   Sum
##         Female 0.334 0.256 0.590
##         Male   0.180 0.230 0.410
##         Sum    0.514 0.486 1.000

Similarly, proportion table below suggests that out of all female students 56.7% did not participate in any extracurricular activity, while 43.3% did.

addmargins(round(prop.table(results$observed, 1), 3), 2)
##               
## mydata1$Gender    No   Yes   Sum
##         Female 0.567 0.433 1.000
##         Male   0.440 0.560 1.000

Table below suggest that out of all students that did not participate in any extracurricular activity 65% were female and 35% were male.

addmargins(round(prop.table(results$observed, 2), 3), 1)
##               
## mydata1$Gender    No   Yes
##         Female 0.650 0.527
##         Male   0.350 0.473
##         Sum    1.000 1.000

For examining the effect size, Cramer’s V statistics was used. It shows that effect size in this case is small.

library(effectsize)
## Warning: package 'effectsize' was built under R version 4.3.2
## 
## Attaching package: 'effectsize'
## The following object is masked from 'package:psych':
## 
##     phi
effectsize::cramers_v(mydata1$Gender, mydata1$Extracurricular_Activities)
## Cramer's V (adj.) |       95% CI
## --------------------------------
## 0.12              | [0.05, 1.00]
## 
## - One-sided CIs: upper bound fixed at [1.00].
interpret_cramers_v(0.12)
## [1] "small"
## (Rules: funder2019)

We proceed to non-parametric test. The null hypothesis is that there is no association between two variables or that odds ratios are equal to one. However, we reject the null hypothesis at p-value = 0.0018. It is important to note that non-parametric test was not needed since all requirements were satisfied (observations are independent, all expected frequencies are greater than 5). That being said, parametric test in this case is more appropriate. However, we came to the same conclusion - answer to research question is yes, there is association between gender and extracurricular activities exist.

fisher.test(mydata1$Gender, mydata1$Extracurricular_Activities)
## 
##  Fisher's Exact Test for Count Data
## 
## data:  mydata1$Gender and mydata1$Extracurricular_Activities
## p-value = 0.001823
## alternative hypothesis: true odds ratio is not equal to 1
## 95 percent confidence interval:
##  1.199554 2.310850
## sample estimates:
## odds ratio 
##   1.663476

Part 2

Data set airquality from R data sets was taken. The first 10 rows are presented below. Data set includes variables: ozone (ozone levels measured in parts per billion (ppb)), solar.r (solar radiation measured in calories per square centimeter), wind (average daily wind speed in miles per hour), temperature (max daily temperature in degrees Fahrenheit), month of the year and day of the month.

Ozone is the independent variable.

Solar radiation is the first explanatory variable. It provides energy for chemical reactions that can lead to the production of ozone. Thus, it is expected that higher solar radiation levels will imply higher ozone levels. Wind speed is the second explanatory variable. It plays a crucial role in dispersing pollutants in the atmosphere. Higher wind speeds may lead to better dispersion and lower concentrations of pollutants, including ozone precursors. Consequently, a negative relationship between wind speed and ozone level is expected. Temperature the third explanatory variable. It is associated with the formation of ozone in the atmosphere. Therefore, a positive relationship between temperature and ozone level is expected. Below we can see first 10 rows of data set.

data("airquality")
mydata2 <- airquality
head(mydata2, 10)
##    Ozone Solar.R Wind Temp Month Day
## 1     41     190  7.4   67     5   1
## 2     36     118  8.0   72     5   2
## 3     12     149 12.6   74     5   3
## 4     18     313 11.5   62     5   4
## 5     NA      NA 14.3   56     5   5
## 6     28      NA 14.9   66     5   6
## 7     23     299  8.6   65     5   7
## 8     19      99 13.8   59     5   8
## 9      8      19 20.1   61     5   9
## 10    NA     194  8.6   69     5  10

Since there were some missing values in data set, they were removed.

library(tidyr)
mydata2 <- drop_na(mydata2)

Descriptive data rounded to 2 decimals is presented below (only for 4 variables that will be included in regression, that is why others were removed as seen below). For example, we can see that Ozone has the highest variance since its coefficient of variation is 0.71. We also see that the average ozone level is 40.29 ppb.

library(pastecs)
## 
## Attaching package: 'pastecs'
## The following object is masked from 'package:tidyr':
## 
##     extract
round(stat.desc((mydata2[c(-5, -6, -7, -8, -9)] ), -1), 2)
##                Ozone Solar.R  Wind  Temp
## median         31.00  207.00  9.70 79.00
## mean           42.10  184.80  9.94 77.79
## SE.mean         3.16    8.65  0.34  0.90
## CI.mean.0.95    6.26   17.15  0.67  1.79
## var          1107.29 8308.74 12.66 90.82
## std.dev        33.28   91.15  3.56  9.53
## coef.var        0.79    0.49  0.36  0.12

Research question: How solar radiation, wind, and temperature affect ozone levels? Two coefficients are statistically significant, but one is not.

If wind increases by 1mph, ozone level will on average decrease by 3.3ppb, holding everything else same. However, if temperature increases by 1F, ozone level will on average increase by 1.65ppb, assuming everything else stays the same.

Coefficient of determination implies that 60.59% of variability of ozone level is explained by linear effect of solar radiation, temperature and wind.

Population determination coefficient > 0, so we can claim that linear relationship between variables exist (at p-value = 0.00000000000000022).

fit = lm(Ozone ~ Solar.R + Wind + Temp, data = mydata2)
summary(fit)
## 
## Call:
## lm(formula = Ozone ~ Solar.R + Wind + Temp, data = mydata2)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -40.485 -14.219  -3.551  10.097  95.619 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -64.34208   23.05472  -2.791  0.00623 ** 
## Solar.R       0.05982    0.02319   2.580  0.01124 *  
## Wind         -3.33359    0.65441  -5.094 1.52e-06 ***
## Temp          1.65209    0.25353   6.516 2.42e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 21.18 on 107 degrees of freedom
## Multiple R-squared:  0.6059, Adjusted R-squared:  0.5948 
## F-statistic: 54.83 on 3 and 107 DF,  p-value: < 2.2e-16

Correlation matrix is presented below in form of scatterplot (same 4 variables were excluded as in analysis of descriptive analysis - month, day, standardized residuals and Cooks distances). We can notice that ozone level has positive correlation with both solar radiation and temperature, while it has negative correlation with wind speed.

library(carData)
## Warning: package 'carData' was built under R version 4.3.2
library(car)
## Warning: package 'car' was built under R version 4.3.2
## 
## Attaching package: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
scatterplotMatrix((mydata2[ c(-5, -6, -7, -8, -9) ]), smooth = FALSE)

Multicolinearity is being checked by VIF and GVIF. There is no multicolinearity detected, since both VIFs are close to 1 and GVIF is much less than 2.25.

library(car)
vif(fit)
##  Solar.R     Wind     Temp 
## 1.095253 1.329070 1.431367
mean(vif(fit))
## [1] 1.28523

In the next step, normality is being checked, so histogram of standardized residuals is created. Distribution looks slightly asymmetric to right, and we see potential outlier since some residuals do not fall in range from -3 to +3.

mydata2$StdResidual <- round(rstandard(fit), 3)
mydata2$CooksD <- round(cooks.distance(fit), 3)

hist(mydata2$StdResidual,
xlab = "standardized residuals",
ylab = "Frequency",
main = "Histogram of standardized residuals")

After running Shapiro-WIlk normality test, we can claim that distribution of errors is normal.

shapiro.test(mydata2$StdResidual)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata2$StdResidual
## W = 0.91511, p-value = 2.824e-06

In the next step, histogram of Cooks distances is created. We see that we have both outliers and some units with high impact that should be removed.

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

Three units with the highest standard residual are presented, and they will potentially be removed.

head(mydata2 [order (mydata2$StdResidual),], 3)
##     Ozone Solar.R Wind Temp Month Day StdResidual CooksD
## 102    16     201  8.0   82     9  20      -1.923  0.011
## 62     16      77  7.4   82     8   3      -1.682  0.022
## 28     23     148  8.0   82     6  13      -1.442  0.008

Here six units with the highest Cooks distances are presented. The first unit is both outlier and unit with high impact, while next 7 are only with high impact.

head(mydata2 [order (-mydata2$CooksD),], 10)
##     Ozone Solar.R Wind Temp Month Day StdResidual CooksD
## 77    168     238  3.4   81     8  25       4.623  0.261
## 7       8      19 20.1   61     5   9       1.866  0.100
## 30     37     284 20.7   72     6  17       1.728  0.098
## 34    135     269  4.1   84     7   1       2.801  0.081
## 14      6      78 18.4   57     5  18       1.613  0.053
## 23    115     223  5.7   79     5  30       2.607  0.046
## 107    14      20 16.6   63     9  25       1.386  0.033
## 63    122     255  4.0   89     8   7       1.799  0.032
## 11     18      65 13.2   58     5  15       1.292  0.023
## 65    110     207  8.0   90     8   9       1.909  0.023

All 8 above mentioned units are being removed.

library(dplyr)
## Warning: package 'dplyr' was built under R version 4.3.2
## 
## Attaching package: 'dplyr'
## The following object is masked from 'package:car':
## 
##     recode
## The following objects are masked from 'package:pastecs':
## 
##     first, last
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
mydata2 <- mydata2 %>%
  filter(!Ozone %in% c(168, 6, 37, 135, 8, 115, 14, 122))

Re-check of Cooks distances after removing all units with high impact and outlier shows success since no gaps in histogram are detected now.

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

Since some units were removed, it is necessary to run regression model again. We can notice substantial change in coefficients. Now also solar radiation is statistically significant. Thus we can say that if solar radiation increases by 1 calorie per square centimeter, ozone level on average increases by 0.05ppb, holding everything else constant.

fit1 = lm (Ozone ~ Solar.R + Wind + Temp, data = mydata2)

summary(fit1)
## 
## Call:
## lm(formula = Ozone ~ Solar.R + Wind + Temp, data = mydata2)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -36.925 -11.611  -1.238   9.761  48.472 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -81.62059   18.54931  -4.400 2.83e-05 ***
## Solar.R       0.05553    0.01914   2.901  0.00462 ** 
## Wind         -2.96422    0.59899  -4.949 3.23e-06 ***
## Temp          1.79388    0.20244   8.861 4.48e-14 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 16.14 on 95 degrees of freedom
## Multiple R-squared:  0.6891, Adjusted R-squared:  0.6793 
## F-statistic:  70.2 on 3 and 95 DF,  p-value: < 2.2e-16

Scatterplot of standardized residuals and standardized fitted values indicates that linearity is not violated. Also, it seems like there are no issues with homoskedasticity.

mydata2$StdFitted <- scale(fit1$fitted.values)
install.packages("car")
## Warning: package 'car' is in use and will not be installed
library (car)
scatterplot (y = mydata2$StdResidual, x = mydata2$StdFitted,
ylab = "Standardized residuals",
xlab = "standardized fitted values",
boxplots = FALSE,
regline = FALSE,
smooth = FALSE)
## Warning in plot.window(...): "regline" is not a graphical parameter
## Warning in plot.xy(xy, type, ...): "regline" is not a graphical parameter
## Warning in axis(side = side, at = at, labels = labels, ...): "regline" is not a
## graphical parameter

## Warning in axis(side = side, at = at, labels = labels, ...): "regline" is not a
## graphical parameter
## Warning in box(...): "regline" is not a graphical parameter
## Warning in title(...): "regline" is not a graphical parameter

We run Breusch pagan test to check if there are any issues related to homoskedasticity. We find out that variance is constant, thus no problem is present.

library(olsrr)
## Warning: package 'olsrr' was built under R version 4.3.2
## 
## Attaching package: 'olsrr'
## The following object is masked from 'package:datasets':
## 
##     rivers
ols_test_breusch_pagan(fit1)
## 
##  Breusch Pagan Test for Heteroskedasticity
##  -----------------------------------------
##  Ho: the variance is constant            
##  Ha: the variance is not constant        
## 
##               Data                
##  ---------------------------------
##  Response : Ozone 
##  Variables: fitted values of Ozone 
## 
##         Test Summary         
##  ----------------------------
##  DF            =    1 
##  Chi2          =    1.118337 
##  Prob > Chi2   =    0.2902768

New regression model is being run, this time without solar radiation.

fit2 = lm (Ozone ~ Wind + Temp, data = mydata2)
summary(fit2)
## 
## Call:
## lm(formula = Ozone ~ Wind + Temp, data = mydata2)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -37.845 -12.231  -1.156  11.466  49.911 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -87.1481    19.1509  -4.551 1.57e-05 ***
## Wind         -2.7750     0.6180  -4.490 1.98e-05 ***
## Temp          1.9699     0.2005   9.827 3.51e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 16.75 on 96 degrees of freedom
## Multiple R-squared:  0.6616, Adjusted R-squared:  0.6545 
## F-statistic: 93.84 on 2 and 96 DF,  p-value: < 2.2e-16

We are now comparing model with and without solar radiation. After analysis of variance, we can claim that the model with solar radiation is better (null hypothesis rejected at p-value = 0.004).

anova(fit1, fit2)
## Analysis of Variance Table
## 
## Model 1: Ozone ~ Solar.R + Wind + Temp
## Model 2: Ozone ~ Wind + Temp
##   Res.Df   RSS Df Sum of Sq      F   Pr(>F)   
## 1     95 24752                                
## 2     96 26946 -1   -2193.4 8.4185 0.004616 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1