That Homework was turned in by Fabian Roth
Exercise 1 #This is to research if the gender makes a difference in grades
source of Data is https://www.kaggle.com/datasets/thedevastator/pisa-performance-scores-by-country/data found on 27.12.2023
LOCATION: This column represents country alpha-3 codes. OAVG indicates an average across all OECD countries.
INDICATOR: The performance indicator being measured can be one of three options: Reading performance (PISAREAD), Mathematical performance (PISAMATH), or Scientific performance (PISASCIENCE).
SUBJECT: This column categorizes subjects as BOY (boys), GIRL (girls), or TOT (total). It indicates which group’s scores are being considered.
TIME: The year in which the performance scores were measured can range from 2000 to 2018.
Value: The mean score of the performance indicator for a specific subject and year is provided in this column as a floating-point number.
Ho: µG = µB H1: µG =/ µB
Alpha = 5%
Removal of Data not relevant –> removal of the value Total in variable subject
Removed Total Data with below code, but since I had to knit it again it refused to properly work since it said Data was already removed, causing constant errors when trying to knit
OECD_PISA_data <- read.table("./OECD PISA data.csv", header = TRUE, dec = ".", sep = ",")
OECD_PISA_data <- OECD_PISA_data[OECD_PISA_data$SUBJECT != "TOT", ]
head(OECD_PISA_data)
## index LOCATION INDICATOR SUBJECT TIME Value
## 1 0 AUS PISAMATH BOY 2003 527.000
## 2 1 AUS PISAMATH BOY 2006 527.000
## 3 2 AUS PISAMATH BOY 2009 519.000
## 4 3 AUS PISAMATH BOY 2012 510.115
## 5 4 AUS PISAMATH BOY 2015 497.000
## 6 5 AUS PISAMATH BOY 2018 494.000
Variable is numeric Test of normality
HO: normal distribution H1: No normal distribution
library(ggplot2)
## Warning: Paket 'ggplot2' wurde unter R Version 4.3.2 erstellt
shapiro_test_B <- shapiro.test(OECD_PISA_data$Value[OECD_PISA_data$SUBJECT == "BOY"])
shapiro_test_G <- shapiro.test(OECD_PISA_data$Value[OECD_PISA_data$SUBJECT == "GIRL"])
print("Shapiro-Wilk Test for 'BOY' group:")
## [1] "Shapiro-Wilk Test for 'BOY' group:"
print(shapiro_test_B)
##
## Shapiro-Wilk normality test
##
## data: OECD_PISA_data$Value[OECD_PISA_data$SUBJECT == "BOY"]
## W = 0.93712, p-value < 2.2e-16
print("\nShapiro-Wilk Test for 'GIRL' group:")
## [1] "\nShapiro-Wilk Test for 'GIRL' group:"
print(shapiro_test_G)
##
## Shapiro-Wilk normality test
##
## data: OECD_PISA_data$Value[OECD_PISA_data$SUBJECT == "GIRL"]
## W = 0.90147, p-value < 2.2e-16
H0 can be rejected. Data is not normally distributed, but since n>30 it is no problem to proceed with Parametric test
library(psych)
## Warning: Paket 'psych' wurde unter R Version 4.3.2 erstellt
##
## Attache Paket: 'psych'
## Die folgenden Objekte sind maskiert von 'package:ggplot2':
##
## %+%, alpha
describeBy(OECD_PISA_data$Value, OECD_PISA_data$SUBJECT)
##
## Descriptive statistics by group
## group: BOY
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 693 483.11 38.55 491 487.08 29.65 358 564 206 -0.94 0.73 1.46
## ------------------------------------------------------------
## group: GIRL
## vars n mean sd median trimmed mad min max range skew kurtosis se
## X1 1 693 492.32 39.49 500 497.36 26.69 348 574 226 -1.19 1.34 1.5
Since samples are independent and ranges are different –> apply Welch correction
library(dplyr)
##
## Attache Paket: 'dplyr'
## Die folgenden Objekte sind maskiert von 'package:stats':
##
## filter, lag
## Die folgenden Objekte sind maskiert von 'package:base':
##
## intersect, setdiff, setequal, union
filtered <- OECD_PISA_data %>% #%>% is used to chain together multiple operations in one line
dplyr::filter(SUBJECT == "GIRL") %>%
dplyr::mutate(Value = ifelse(!is.na(Value), Value * sqrt(206 / 226), Value)) #mutate: redefine value and filter out NA that occured
t_test <- t.test(OECD_PISA_data$Value[OECD_PISA_data$SUBJECT == "BOY"], OECD_PISA_data$Value[OECD_PISA_data$SUBJECT == "GIRL"])
print("\nT-Test Results:")
## [1] "\nT-Test Results:"
print(t_test)
##
## Welch Two Sample t-test
##
## data: OECD_PISA_data$Value[OECD_PISA_data$SUBJECT == "BOY"] and OECD_PISA_data$Value[OECD_PISA_data$SUBJECT == "GIRL"]
## t = -4.3925, df = 1383.2, p-value = 1.206e-05
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -13.320409 -5.095759
## sample estimates:
## mean of x mean of y
## 483.1099 492.3179
library(ggplot2)
ggplot(OECD_PISA_data, aes(x = SUBJECT, y = Value, fill = SUBJECT)) +
geom_boxplot() +
labs(x = "Gender (SUBJECT)", y = "Test result", fill = "Gender")
wilcox_test_result <- wilcox.test(OECD_PISA_data$Value ~ OECD_PISA_data$SUBJECT, data = OECD_PISA_data)
print(wilcox_test_result)
##
## Wilcoxon rank sum test with continuity correction
##
## data: OECD_PISA_data$Value by OECD_PISA_data$SUBJECT
## W = 197562, p-value = 1.111e-08
## alternative hypothesis: true location shift is not equal to 0
Since all requirements are met for the parametric test you want to go for it as it tells more. Assuming all other variables stay the same, we can reject H0. Girls on average do 9,2points better in the PISA-Test, than boys on average do at p-value >0,001.
Exercise 2
soruce of Data is https://www.kaggle.com/datasets/henryshan/student-performance-prediction/data found on 27.12.2023
school student’s school (binary: ‘GP’ - Gabriel Pereira or ‘MS’ - Mousinho da Silveira) sex student’s sex (binary: ‘F’ - female or ‘M’ - male) age student’s age (numeric: from 15 to 22) address student’s home address type (binary: ‘U’ - urban or ‘R’ - rural) famsize family size (binary: ‘LE3’ - less or equal to 3 or ‘GT3’ - greater than 3) Pstatus parent’s cohabitation status (binary: ‘T’ - living together or ‘A’ - apart) Medu mother’s education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education) Fedu father’s education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education) Mjob mother’s job (nominal: ‘teacher’, ‘health’ care related, civil ‘services’ (e.g. administrative or police), ‘at_home’ or ‘other’) Fjob father’s job (nominal: ‘teacher’, ‘health’ care related, civil ‘services’ (e.g. administrative or police), ‘at_home’ or ‘other’) reason reason to choose this school (nominal: close to ‘home’, school ‘reputation’, ‘course’ preference or ‘other’) guardian student’s guardian (nominal: ‘mother’, ‘father’ or ‘other’) traveltime home to school travel time (numeric: 1 - <15 min., 2 - 15 to 30 min., 3 - 30 min. to 1 hour, or 4 - >1 hour) studytime weekly study time (numeric: 1 - <2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - >10 hours) failures number of past class failures (numeric: n if 1<=n<3, else 4) schoolsup extra educational support (binary: yes or no) famsup family educational support (binary: yes or no) paid extra paid classes within the course subject (Math or Portuguese) (binary: yes or no) activities extra-curricular activities (binary: yes or no) nursery attended nursery school (binary: yes or no) higher wants to take higher education (binary: yes or no) internet Internet access at home (binary: yes or no) romantic with a romantic relationship (binary: yes or no) famrel quality of family relationships (numeric: from 1 - very bad to 5 - excellent) freetime free time after school (numeric: from 1 - very low to 5 - very high) goout going out with friends (numeric: from 1 - very low to 5 - very high) Dalc workday alcohol consumption (numeric: from 1 - very low to 5 - very high) Walc weekend alcohol consumption (numeric: from 1 - very low to 5 - very high) health current health status (numeric: from 1 - very bad to 5 - very good) absences number of school absences (numeric: from 0 to 93) these grades are related with the course subject, Math or Portuguese: G1 - first period grade (numeric: from 0 to 20) G2 - second period grade (numeric: from 0 to 20) G3 - final grade (numeric: from 0 to 20, output target)
#This is to investigate how the way stundets spend their time influcences their grades.
For the purpose of this exercise we will only review the follwing variables
Dependent variable G3
Explanatory Study time - which is expected to influence the grade in a positive way. goout - which is expected to influence the grade in a negative way. Free time - which is expected to influence the grade in a negative way. absence - which is expected to influence the grade in a negative way. sex - which is expected to influence the grade
mat2 <- read.table("./mat2.csv", header = TRUE, dec = ".", sep = ",")
summary(mat2)
## X school sex age
## Min. : 0.0 Length:395 Length:395 Min. :15.0
## 1st Qu.: 98.5 Class :character Class :character 1st Qu.:16.0
## Median :197.0 Mode :character Mode :character Median :17.0
## Mean :197.0 Mean :16.7
## 3rd Qu.:295.5 3rd Qu.:18.0
## Max. :394.0 Max. :22.0
## address famsize Pstatus Medu
## Length:395 Length:395 Length:395 Min. :0.000
## Class :character Class :character Class :character 1st Qu.:2.000
## Mode :character Mode :character Mode :character Median :3.000
## Mean :2.749
## 3rd Qu.:4.000
## Max. :4.000
## Fedu Mjob Fjob reason
## Min. :0.000 Length:395 Length:395 Length:395
## 1st Qu.:2.000 Class :character Class :character Class :character
## Median :2.000 Mode :character Mode :character Mode :character
## Mean :2.522
## 3rd Qu.:3.000
## Max. :4.000
## guardian traveltime studytime failures
## Length:395 Min. :1.000 Min. :1.000 Min. :0.0000
## Class :character 1st Qu.:1.000 1st Qu.:1.000 1st Qu.:0.0000
## Mode :character Median :1.000 Median :2.000 Median :0.0000
## Mean :1.448 Mean :2.035 Mean :0.3342
## 3rd Qu.:2.000 3rd Qu.:2.000 3rd Qu.:0.0000
## Max. :4.000 Max. :4.000 Max. :3.0000
## schoolsup famsup paid activities
## Length:395 Length:395 Length:395 Length:395
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
##
##
##
## nursery higher internet romantic
## Length:395 Length:395 Length:395 Length:395
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
##
##
##
## famrel freetime goout Dalc
## Min. :1.000 Min. :1.000 Min. :1.000 Min. :1.000
## 1st Qu.:4.000 1st Qu.:3.000 1st Qu.:2.000 1st Qu.:1.000
## Median :4.000 Median :3.000 Median :3.000 Median :1.000
## Mean :3.944 Mean :3.235 Mean :3.109 Mean :1.481
## 3rd Qu.:5.000 3rd Qu.:4.000 3rd Qu.:4.000 3rd Qu.:2.000
## Max. :5.000 Max. :5.000 Max. :5.000 Max. :5.000
## Walc health absences G1
## Min. :1.000 Min. :1.000 Min. : 0.000 Min. : 3.00
## 1st Qu.:1.000 1st Qu.:3.000 1st Qu.: 0.000 1st Qu.: 8.00
## Median :2.000 Median :4.000 Median : 4.000 Median :11.00
## Mean :2.291 Mean :3.554 Mean : 5.709 Mean :10.91
## 3rd Qu.:3.000 3rd Qu.:5.000 3rd Qu.: 8.000 3rd Qu.:13.00
## Max. :5.000 Max. :5.000 Max. :75.000 Max. :19.00
## G2 G3
## Min. : 0.00 Min. : 0.00
## 1st Qu.: 9.00 1st Qu.: 8.00
## Median :11.00 Median :11.00
## Mean :10.71 Mean :10.42
## 3rd Qu.:13.00 3rd Qu.:14.00
## Max. :19.00 Max. :20.00
fit1 <- lm(G3 ~ studytime + freetime + goout + absences,
data = mat2)
summary(fit1)
##
## Call:
## lm(formula = G3 ~ studytime + freetime + goout + absences, data = mat2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -12.880 -1.861 0.319 2.997 8.792
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 9.96372 1.14299 8.717 < 2e-16 ***
## studytime 0.55537 0.27553 2.016 0.04452 *
## freetime 0.32700 0.24125 1.355 0.17605
## goout -0.61271 0.21434 -2.859 0.00448 **
## absences 0.02940 0.02869 1.025 0.30612
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 4.53 on 390 degrees of freedom
## Multiple R-squared: 0.03229, Adjusted R-squared: 0.02236
## F-statistic: 3.253 on 4 and 390 DF, p-value: 0.01212
#install.packages(car)
library(car)
## Warning: Paket 'car' wurde unter R Version 4.3.2 erstellt
## Lade nötiges Paket: carData
## Warning: Paket 'carData' wurde unter R Version 4.3.2 erstellt
##
## Attache Paket: 'car'
## Das folgende Objekt ist maskiert 'package:dplyr':
##
## recode
## Das folgende Objekt ist maskiert 'package:psych':
##
## logit
scatterplotMatrix(~ G3 + studytime + freetime + goout + absences, data = mat2, smooth = FALSE)
fit1 <- lm(G3 ~ studytime + freetime + goout + absences, data = mat2)
#install.packages("car")
library(car)
vif(fit1)
## studytime freetime goout absences
## 1.026642 1.114918 1.093270 1.012490
mean(vif(fit1))
## [1] 1.06183
all vifs are very low –> okay to proceed
mat2$StdResid <- round(rstandard(fit1),3)
mat2$CooksD <- round(cooks.distance(fit1),3)
hist(mat2$StdResid,
xlab = "Standard residuals",
ylab = "Frequency",
main = "Histogram of std residuals")
All
data is within -3 to +3 and there is no gaps, so no need to remove any
values
shapiro.test(mat2$StdResid)
##
## Shapiro-Wilk normality test
##
## data: mat2$StdResid
## W = 0.94953, p-value = 2.313e-10
Ho: Errors are normally distributed H1: They´re not
–> Errors are not normally distributed at p-value >0,001 –> since sample size is >30 it is not a problem and we can proceed
hist(mat2$CooksD,
xlab = "Cooks distance",
ylab = "Frequency",
main = "Histogram of Cook distances")
There
is unit(s) with high impact
head(mat2[order(-mat2$CooksD),],6)
## X school sex age address famsize Pstatus Medu Fedu Mjob Fjob
## 260 259 GP F 17 U LE3 T 2 2 services services
## 277 276 GP F 18 R GT3 A 3 2 other services
## 141 140 GP M 15 U GT3 T 4 3 teacher services
## 335 334 GP F 18 R GT3 T 2 2 at_home other
## 390 389 MS F 18 U GT3 T 1 1 other other
## 169 168 GP F 16 U GT3 T 2 2 other other
## reason guardian traveltime studytime failures schoolsup famsup paid
## 260 course father 1 4 0 no no yes
## 277 home mother 2 2 0 no no no
## 141 course father 2 4 0 yes yes no
## 335 course mother 2 4 0 no no no
## 390 course mother 2 2 1 no no no
## 169 home mother 1 2 0 no yes yes
## activities nursery higher internet romantic famrel freetime goout Dalc Walc
## 260 yes yes yes yes yes 3 4 1 1 1
## 277 no no no yes yes 4 1 1 1 1
## 141 no yes yes yes no 2 2 2 1 1
## 335 yes yes yes no no 4 4 4 1 1
## 390 yes yes yes no no 1 1 1 1 1
## 169 no no yes yes no 5 1 5 1 1
## health absences G1 G2 G3 StdResid CooksD
## 260 2 0 10 9 0 -2.889 0.054
## 277 5 75 10 9 9 -0.992 0.052
## 141 3 0 7 9 0 -2.590 0.028
## 335 4 0 10 9 0 -2.464 0.027
## 390 5 0 6 5 0 -2.408 0.026
## 169 4 0 6 7 0 -1.872 0.024
–> remove units 259 and 276 –> caused new gaps –> had to remove several additional units
library(dplyr)
mat2_filtered <- subset(mat2, !(X %in% c(259, 276, 140, 168, 334, 389, 367, 183, 198, 343, 387))) #selects variables - in this case to exclude some
hist(mat2_filtered$CooksD,
xlab = "Cooks distance",
ylab = "Frequency",
main = "Histogram of Cook distances")
head(mat2_filtered[order(-mat2_filtered$CooksD),],6)
## X school sex age address famsize Pstatus Medu Fedu Mjob Fjob
## 48 47 GP M 16 U GT3 T 4 3 health services
## 131 130 GP F 15 R GT3 T 3 4 services teacher
## 154 153 GP M 19 U GT3 T 3 2 services at_home
## 92 91 GP F 15 U GT3 T 4 3 services other
## 114 113 GP M 15 U LE3 T 4 2 teacher other
## 130 129 GP M 16 R GT3 T 4 4 teacher teacher
## reason guardian traveltime studytime failures schoolsup famsup paid
## 48 reputation mother 1 4 0 no no no
## 131 course father 2 3 2 no yes no
## 154 home mother 1 1 3 no yes no
## 92 reputation mother 1 1 0 no no yes
## 114 course mother 1 1 0 no no no
## 130 course mother 1 1 0 no no yes
## activities nursery higher internet romantic famrel freetime goout Dalc Walc
## 48 yes yes yes yes no 4 2 2 1 1
## 131 no yes yes yes yes 4 2 2 2 2
## 154 no yes no yes yes 4 5 4 1 1
## 92 yes yes yes yes no 4 5 5 1 3
## 114 no yes yes yes no 3 5 2 1 1
## 130 yes yes yes yes no 3 5 5 2 5
## health absences G1 G2 G3 StdResid CooksD
## 48 2 4 19 19 20 1.843 0.014
## 131 5 0 12 0 0 -2.455 0.014
## 154 4 0 5 0 0 -2.158 0.014
## 92 1 4 16 17 18 1.957 0.013
## 114 3 10 18 19 19 1.735 0.013
## 130 4 8 18 18 18 1.931 0.013
filtered_indices <- which(mat2$...1 %in% c(259, 276, 140, 168, 334, 389, 367, 183, 198, 343, 387)) #which returns the position of the values in the logical vector.
remaining_indices <- setdiff(seq_len(nrow(mat2)), filtered_indices) #setdiff indicates which elements of the data frame X are not existent in the data frame Y
mat2_remaining <- mat2[remaining_indices, ]
fitted_values <- fit1$fitted.values[remaining_indices]
std_fitted_values <- scale(fitted_values)
mat2_remaining$StdFitted <- std_fitted_values
scatterplot(y = mat2_remaining$StdResid, x = mat2_remaining$StdFitted,
ylab = "Standardized residuals",
xlab = "Standardized fitted values",
boxplots = FALSE,
regline = FALSE,
smooth = FALSE)
## Warning in plot.window(...): "regline" ist kein Grafikparameter
## Warning in plot.xy(xy, type, ...): "regline" ist kein Grafikparameter
## Warning in axis(side = side, at = at, labels = labels, ...): "regline" ist kein
## Grafikparameter
## Warning in axis(side = side, at = at, labels = labels, ...): "regline" ist kein
## Grafikparameter
## Warning in box(...): "regline" ist kein Grafikparameter
## Warning in title(...): "regline" ist kein Grafikparameter
fit1_corrected <- lm(G3 ~ studytime + freetime + goout + absences, data = mat2_remaining)
Homostatisity seems to be given
library(olsrr)
## Warning: Paket 'olsrr' wurde unter R Version 4.3.2 erstellt
##
## Attache Paket: 'olsrr'
## Das folgende Objekt ist maskiert '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 : G3
## Variables: fitted values of G3
##
## Test Summary
## ----------------------------
## DF = 1
## Chi2 = 1.964289
## Prob > Chi2 = 0.1610553
As per Breusch Pagan Test we can not reject H0 at p-value > 0,161
mat2_remaining$sexF <- factor(mat2$sex, levels = c("M", "F"))
fit2 <- lm(G3 ~ studytime + freetime + goout + absences + sexF, data = mat2_remaining)
summary(fit2)
##
## Call:
## lm(formula = G3 ~ studytime + freetime + goout + absences + sexF,
## data = mat2_remaining)
##
## Residuals:
## Min 1Q Median 3Q Max
## -12.9550 -1.8561 0.3508 2.9270 9.9607
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 10.63491 1.15598 9.200 < 2e-16 ***
## studytime 0.79252 0.28505 2.780 0.00570 **
## freetime 0.19172 0.24355 0.787 0.43166
## goout -0.61670 0.21236 -2.904 0.00389 **
## absences 0.03589 0.02852 1.259 0.20892
## sexFF -1.40681 0.48711 -2.888 0.00409 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 4.488 on 389 degrees of freedom
## Multiple R-squared: 0.0526, Adjusted R-squared: 0.04042
## F-statistic: 4.32 on 5 and 389 DF, p-value: 0.0007754
anova_result <- anova(fit1_corrected, fit2)
print(anova_result)
## Analysis of Variance Table
##
## Model 1: G3 ~ studytime + freetime + goout + absences
## Model 2: G3 ~ studytime + freetime + goout + absences + sexF
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 390 8002.9
## 2 389 7834.9 1 168 8.3411 0.004093 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Anova shows that model 2 is better
#Answer to the research question: #“The way stundets spend their time only explains about 3,2% of the grade. Model two shows that other factors, such as the gender influence the grade significantly more.”