The data shows performance of 1,000 students on different levels of education in the US. There were 3 subjects tested: math, reading and writing. The data shows students gender, race, level of education, lunch and test preparation. The data has 8 variables of which 5 are considered as categorical variables.
source: Kaggle- Students performance in exams (URL: https://www.kaggle.com/datasets/spscientist/students-performance-in-exams)
Presenting the first 6 rows of the data:
#importing and presenting data
StudentsPerformance <- read.table("./StudentsPerformance.csv", header = TRUE, sep = ",", dec = ".")
str(StudentsPerformance)
## 'data.frame': 1000 obs. of 8 variables:
## $ gender : chr "female" "female" "female" "male" ...
## $ race.ethnicity : chr "group B" "group C" "group B" "group A" ...
## $ parental.level.of.education: chr "bachelor's degree" "some college" "master's degree" "associate's degree" ...
## $ lunch : chr "standard" "standard" "standard" "free/reduced" ...
## $ test.preparation.course : chr "none" "completed" "none" "none" ...
## $ math.score : int 72 69 90 47 76 71 88 40 64 38 ...
## $ reading.score : int 72 90 95 57 78 83 95 43 64 60 ...
## $ writing.score : int 74 88 93 44 75 78 92 39 67 50 ...
head(StudentsPerformance)
## gender race.ethnicity parental.level.of.education lunch test.preparation.course math.score reading.score
## 1 female group B bachelor's degree standard none 72 72
## 2 female group C some college standard completed 69 90
## 3 female group B master's degree standard none 90 95
## 4 male group A associate's degree free/reduced none 47 57
## 5 male group C some college standard none 76 78
## 6 female group B associate's degree standard none 71 83
## writing.score
## 1 74
## 2 88
## 3 93
## 4 44
## 5 75
## 6 78
Explanation of variables:
Of the five categorical variables gender, lunch and test preparation course are binary, race is nominal and parental level of education is ordinal.
#deleting data
StudentsPerformance1 <- StudentsPerformance[ , -2]
head(StudentsPerformance1)
## gender parental.level.of.education lunch test.preparation.course math.score reading.score writing.score
## 1 female bachelor's degree standard none 72 72 74
## 2 female some college standard completed 69 90 88
## 3 female master's degree standard none 90 95 93
## 4 male associate's degree free/reduced none 47 57 44
## 5 male some college standard none 76 78 75
## 6 female associate's degree standard none 71 83 78
Excluding race/ethnicity because the data did not specify what the groups mean.
#renaming variables
colnames(StudentsPerformance1) [2] <- "education"
colnames(StudentsPerformance1) [4] <- "preparation"
#creating new variable
StudentsPerformance1$average <- (StudentsPerformance1$math.score + StudentsPerformance1$writing.score + StudentsPerformance1$reading.score) /3
#descending order of exam points- average
head(StudentsPerformance1[order(-StudentsPerformance1$average), ])
## gender education lunch preparation math.score reading.score writing.score average
## 459 female bachelor's degree standard none 100 100 100 100.00000
## 917 male bachelor's degree standard completed 100 100 100 100.00000
## 963 female associate's degree standard none 100 100 100 100.00000
## 115 female bachelor's degree standard completed 99 100 100 99.66667
## 180 female some high school standard completed 97 100 100 99.00000
## 713 female some college standard none 98 100 99 99.00000
#categorical to numeric
StudentsPerformance1$lunch <- factor(StudentsPerformance1$lunch,
levels = c("standard", "free/reduced"),
labels = c(0, 1))
#including only master's level of education
StudentsPerformance3 <- StudentsPerformance1[StudentsPerformance1$education == "master's degree",]
head(StudentsPerformance3)
## gender education lunch preparation math.score reading.score writing.score average
## 3 female master's degree 0 none 90 95 93 92.66667
## 15 female master's degree 0 none 50 53 58 53.66667
## 19 male master's degree 1 completed 46 42 46 44.66667
## 26 male master's degree 1 none 73 74 72 73.00000
## 30 female master's degree 0 none 62 70 75 69.00000
## 33 female master's degree 1 none 56 72 65 64.33333
summary(StudentsPerformance3[ , c(-1,-2,-3,-4)])
## math.score reading.score writing.score average
## Min. :40.00 Min. : 42.00 Min. : 46.00 Min. :44.67
## 1st Qu.:55.50 1st Qu.: 65.50 1st Qu.: 67.00 1st Qu.:63.17
## Median :73.00 Median : 76.00 Median : 75.00 Median :73.33
## Mean :69.75 Mean : 75.37 Mean : 75.68 Mean :73.60
## 3rd Qu.:81.00 3rd Qu.: 84.50 3rd Qu.: 85.00 3rd Qu.:85.50
## Max. :95.00 Max. :100.00 Max. :100.00 Max. :97.67
#install.packages("pastecs")
library(pastecs)
round(stat.desc(StudentsPerformance1[ , c(-1, -2, -3, -4)]), 2)
## math.score reading.score writing.score average
## nbr.val 1000.00 1000.00 1000.00 1000.00
## nbr.null 1.00 0.00 0.00 0.00
## nbr.na 0.00 0.00 0.00 0.00
## min 0.00 17.00 10.00 9.00
## max 100.00 100.00 100.00 100.00
## range 100.00 83.00 90.00 91.00
## sum 66089.00 69169.00 68054.00 67770.67
## median 66.00 70.00 69.00 68.33
## mean 66.09 69.17 68.05 67.77
## SE.mean 0.48 0.46 0.48 0.45
## CI.mean.0.95 0.94 0.91 0.94 0.88
## var 229.92 213.17 230.91 203.27
## std.dev 15.16 14.60 15.20 14.26
## coef.var 0.23 0.21 0.22 0.21
Excluding all categorical variables for descriptive statistics and using the function stat.desc to show some basic descriptive statistics. We could also use the functions summary or describe.
Explanation of results: - Mean of reading score: the average score on reading test in all levels of education is 96.17 - Median of reading score: 50% of all students got more than 70 points on their reading exam and 50% of students got less that 70 points - Min/Max of writing score: the lowest score in writing exam was 10 points and the highest was 100 points - Range of writing score: the difference between the highest and the lowest score on a writing test so 100-10=90
Number of NAs is 0, so we do not need to delete any data.
#install.packages("modeest")
library(modeest)
mlv(StudentsPerformance1$math.score)
## [1] 65
Calculating mlv = most likely value = mode.
quantile(StudentsPerformance1$math.score, p= 0.8)
## 80%
## 79
The quantile function tell us that 80% of all students got 79 points or less on math exam. We could calculate it for any wanted percentage.
#histogram
hist(StudentsPerformance3$math.score,
main = "Score on exam",
xlab = "Score",
ylab = "Frequency",
breaks = seq(0, 100, 5),
col = "lightyellow")
Showing a histogram of students performance on a math test. We only included students of masters education. We can see that most scored 60 points and above. The histogram is negatively skewed, which indicates that there were more student that scored higher amount of points than student who scored fewer amount of points.
#Boxplot
boxplot(StudentsPerformance3[, c(-1, -2, -3, -4)],
main = "Score on exam",
ylab = "score",
col = "lightyellow")
for math score: - bold black like = median - lower yellow square = 1st quartile - upper yellow square = 3rd quartile - lower line = min - upper line = max - there are no dots above or under the boxplot which indicates that there are no outliers
A researcher examined the effects of online schooling on body weight in ninth graders. Based on data from the 2018/2019 school year, the average weight was 59.5 kg. At the beginning of the 2021/2022 school year, researchers randomly selected 50 ninth graders and measured their weight.
Presenting the first 6 rows of given data with two variables ID and Mass:
Bodymass <- read.table("./Body mass.csv", header = TRUE, sep = ";", dec = ",")
head(Bodymass)
## 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
# Check the result
str(df)
## function (x, df1, df2, ncp, log = FALSE)
library(pastecs)
round(stat.desc(Bodymass[, -1]), 2)
## nbr.val nbr.null nbr.na min max range sum median mean
## 50.00 0.00 0.00 49.70 83.20 33.50 3143.80 62.80 62.88
## SE.mean CI.mean.0.95 var std.dev coef.var
## 0.85 1.71 36.14 6.01 0.10
Presenting basic descriptive statistics with the function stat.desc and excluding variable ID, because it does not make sense to present it. Among other things we can see that the minimum weight is 49.70, the maximum is 83.20 and that the average weight is 62.8. The variance is 36.14 which tells us how much the values are distributed around the mean.
hist_mass = hist(Bodymass$Mass,
main = "Distribution of body mass",
xlab = "Mass in kg",
ylab = "Frequency",
breaks = seq(40, 90, 2),
ylim = c(0, 15),
border = "black",
col = "skyblue")
The histogram is quite normally distributed, maybe a little bit skewed to the left- positively skewed.
test_Mi <- t.test(Bodymass$Mass, mu = 59.5)
print(test_Mi)
##
## One Sample t-test
##
## data: Bodymass$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
H0: mu = 59.5
H1: mu != 59.5
alpha = 5%
P < 0.05 – we reject H0, p < 0.001 –strong evidence that H1 = TRUE
We can say that on average the average weight of students is not 59.5. It has increased from previous years from 59.5 to 62.8.
#install.packages("effectsize")
library(effectsize)
## Registered S3 method overwritten by 'parameters':
## method from
## predict.kmeans statip
cohens_d(Bodymass$Mass, mu = 59.5)
## Cohen's d | 95% CI
## ------------------------
## 0.56 | [0.26, 0.86]
##
## - Deviation from a difference of 59.5.
Copens_d value of 0.56 is considered as a medium effect size (Sawilowsky standards).
You analyse the price per m2 for a sample of apartments in the Ljubljana region. Follow the questions in R Markdown included in the folder.
#install.packages("readxl")
library(readxl)
apartments <- read_xlsx("./Apartments.xlsx")
apartments <- as.data.frame(apartments)
head(apartments)
## 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:
apartments$ParkingF <- factor(apartments$Parking,
levels = c (0, 1),
labels = c ("no", "yes"))
apartments$BalconyF <- factor(apartments$Balcony,
levels = c (0, 1),
labels = c ("no", "yes"))
head(apartments)
## Age Distance Price Parking Balcony ParkingF BalconyF
## 1 7 28 1640 0 1 no yes
## 2 18 1 2800 1 0 yes no
## 3 7 28 1660 0 0 no no
## 4 28 29 1850 0 1 no yes
## 5 18 18 1640 1 1 yes yes
## 6 28 12 1770 0 1 no yes
test_Mu <- t.test(apartments$Price, mu = 1900)
print(test_Mu)
##
## One Sample t-test
##
## data: apartments$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
Stating the null and alternative hypothesis: Null hypothesis: H0: Mu_Price = 1900 eur
Alternative hypothesis:
H1: Mu_Price != 1900 eur
alpha = 0.05
We reject the null hypothesis because p = 0.0047, Mu is different than 1900.
fit1 <- lm(Price ~ Age,
data = apartments)
summary(fit1)
##
## Call:
## lm(formula = Price ~ Age, data = apartments)
##
## 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
cor(apartments$Price, apartments$Age)
## [1] -0.230255
regression function:
Price = 2185.455 - 8.975 (Age)
H0: beta1 = 0 (age has no affect on price)
H1: beta1 != 0 (age has an effect on price)
p = 0.034
We can reject H0 because p < 0.05. This tells us that age is significant fot the price of an apartment.
if on average the apartment ages for one year, the price of that apartment decreases by 8.975 for m2, (p < 0,05) assuming that other variables remain the same.
There is weak negative linear correlation between the two variables.
r2 is a number between 0-1 and it tells us how much of the dependent variable is explained by the effect of explanatory variables.
5% of variability of price per m2 can be explained by the affect of age of an apartment.
#install.packages("car")
library(car)
## Loading required package: carData
scatterplotMatrix(apartments[, -c(4, 5, 6, 7, 8) ],
smooth = FALSE)
Based on the graphs none of the explanatory variables look too strongly correlated. We will make sure with VIF later.
#install.packages("Hmisc")
library(Hmisc)
##
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:base':
##
## format.pval, units
rcorr(as.matrix(apartments[, -c(4, 5, 6, 7, 8) ]))
## Age Distance Price
## Age 1.00 0.04 -0.23
## Distance 0.04 1.00 -0.63
## Price -0.23 -0.63 1.00
##
## n= 85
##
##
## P
## Age Distance Price
## Age 0.6966 0.0340
## Distance 0.6966 0.0000
## Price 0.0340 0.0000
Pearson correlation coefficient
Between the two observed variables Age and Distance there is no strong correlations that shows signs of multicolinearity.
fit2 <- lm(Price ~ Age + Distance,
data = apartments)
vif(fit2)
## Age Distance
## 1.001845 1.001845
apartments$StdResid <- round(rstandard(fit2), 3)
apartments$CooksD <- round(cooks.distance(fit2), 3)
hist(apartments$CooksD,
xlab = "Cooks distance",
ylab = "Frequency",
main = "Histogram of cook's distance",
col = "skyblue")
We can see that some units that have significantly larger cooks distance than others. We will make an descending order to find out which ID we need to remove.
head(apartments[order(-apartments$CooksD), ], 10)
## 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
## 58 8 2 2820 1 0 yes no 1.655 0.037
## 25 8 26 2300 1 1 yes yes 1.571 0.034
## 57 10 1 2810 0 0 no no 1.601 0.032
## 2 18 1 2800 1 0 yes no 1.783 0.030
We will remove the apartments with ID 38, 54 because their values are significantly higher than others.
apartments <- apartments[-38, ]
apartments <- apartments[-54, ]
hist(apartments$CooksD,
xlab = "Cooks distance",
ylab = "Frequency",
main = "Histogram of cook's distance",
col = "skyblue")
When we remove these two units and rerun histogram and we can see that the distribution is continous.
hist(apartments$StdResid,
xlab = "Standardized residuals",
ylab = "Frequency",
main = "Histogram of standardized residuals",
col = "skyblue")
We can see that no value in under -3 or above 3 which means we do not have any outliers.
fit2 <- lm(Price ~ Age + Distance,
data = apartments)
apartments$StdFitted <- scale(fit2$fitted.values)
library(ggplot2)
ggplot(apartments, aes(x = StdFitted, y = StdResid)) +
geom_point() +
labs(x = "Standardized fitted values",
y = "Standardized residuals") +
theme_minimal()
We can not be sure about heteroskedasticity from the graph so we do the Breusch Pagan test.
#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 = 3.775135
## Prob > Chi2 = 0.05201969
p = 19% so it is much higher than we normally use- we do not reject H0. That means that we do not have problems with heteroskedasticity.
hist(apartments$StdResid,
xlab = "Standardized residuals",
ylab = "Frequency",
main = "Histogram of standardized residuals",
col = "skyblue")
shapiro.test(apartments$StdResid)
##
## Shapiro-Wilk normality test
##
## data: apartments$StdResid
## W = 0.94963, p-value = 0.002636
p < 0.05 - we can reject null hypothesis – standardized residuals are not normally distributed which is not that important because sample size > 30 units.
summary(fit2)
##
## Call:
## lm(formula = Price ~ Age + Distance, data = apartments)
##
## Residuals:
## Min 1Q Median 3Q Max
## -627.27 -212.96 -46.23 205.05 578.98
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2490.112 76.189 32.684 < 2e-16 ***
## Age -7.850 3.244 -2.420 0.0178 *
## Distance -23.945 2.826 -8.473 9.53e-13 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 273.5 on 80 degrees of freedom
## Multiple R-squared: 0.4968, Adjusted R-squared: 0.4842
## F-statistic: 39.49 on 2 and 80 DF, p-value: 1.173e-12
cor(apartments$Price, apartments$Age)
## [1] -0.2126404
H1: beta 1 != 0
p < 0.05
If on average the apartment ages for one year, the price of that apartment on average decreases by 7.850eur per m2, (p < 0,05) assuming that distance remains the same.
H1: beta 2 != 0
p < 0.001
If on average the distance from city center increases for 1km, the price of that apartment decreases by 23.945eur per m2, (p < 0,001) assuming that age remains the same.
49.68% of variability of price per m2 can be explained by the affect of age and distance of an apartment.
There is weak negative linear correlation between the two variables.
fit3 <- lm(Price ~ Age + Distance + ParkingF + BalconyF,
data = apartments)
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 80 5982100
## 2 78 5458696 2 523404 3.7395 0.02813 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
H0: model f2 is better
H1: model f3 is better
p < 0.001 ; we reject the null hypothesis
f3 is better than f2
summary(fit3)
##
## Call:
## lm(formula = Price ~ Age + Distance + ParkingF + BalconyF, data = apartments)
##
## Residuals:
## Min 1Q Median 3Q Max
## -499.06 -194.33 -32.04 219.03 544.31
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2358.900 93.664 25.185 < 2e-16 ***
## Age -7.197 3.148 -2.286 0.02499 *
## Distance -21.241 2.911 -7.296 2.14e-10 ***
## ParkingFyes 168.921 62.166 2.717 0.00811 **
## BalconyFyes -6.985 58.745 -0.119 0.90566
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 264.5 on 78 degrees of freedom
## Multiple R-squared: 0.5408, Adjusted R-squared: 0.5173
## F-statistic: 22.97 on 4 and 78 DF, p-value: 1.449e-12
P value for balcony p > 0.05 – we can not say that balcony has statistical effect on life expectancy.
estimate of regression coefficient: Parking If on average apartment has a parking spot, the apartment on average cheaper by 168.921$ per m2 (p = 0.008), assuming all other explanatory variables, included in the model are constant.
estimate of regression coefficient: Balcony If on average apartment has a balcony, the apartment is on average cheaper by 6.985$ per m2 (p = 0.906), assuming all other explanatory variables, included in the model are constant.
F-statistics: test of significance of regression:
H0: Ro2 = 0 ; you don’t exlpain anything with your model
H1: Ro2 > 0
F = 22.97, p < 0.001
We reject null hypothesis at p < 0.001. We can say that the population coefficient of determination is more than 0 meaning that we found linear relationship between Price od an apartment and explanatory variables, included in the model.
apartments$Fitted <- fitted.values(fit3)
apartments$Residuals <- residuals(fit3)
head(apartments$Residuals[2])
## [1] 422.9572
Residual for apartment ID2 = 422.9572