Find your own data set that contains at least 30 units and at least 4
variables (most of which are numeric, but it is good to have at least
one categorical variable as well). Perform the following steps using the
R program:
1. Explain the data set (the variables used in the
analysis).
2. Perform some data manipulations (create new variable,
delete some units due to missing data, rename variables, create new
data.frame based on conditions, etc.).
3. Present the descriptive
statistics for your variables and explain at least 3 different sample
statistics (mean, median, etc.).
4. Graph the distribution of the
variables using histograms, scatterplots, and/or boxplots. Explain the
findings.
#data(package = .packages(all.available = TRUE))
mydata <- force(Highway1)
head(mydata, 10)
## rate len adt trks sigs1 slim shld lane acpt itg lwid htype
## 1 4.58 4.99 69 8 0.20040080 55 10 8 4.6 1.20 12 FAI
## 2 2.86 16.11 73 8 0.06207325 60 10 4 4.4 1.43 12 FAI
## 3 3.02 9.75 49 10 0.10256410 60 10 4 4.7 1.54 12 FAI
## 4 2.29 10.65 61 13 0.09389671 65 10 6 3.8 0.94 12 FAI
## 5 1.61 20.01 28 12 0.04997501 70 10 4 2.2 0.65 12 FAI
## 6 6.87 5.97 30 6 2.00750419 55 10 4 24.8 0.34 12 PA
## 7 3.85 8.57 46 8 0.81668611 55 8 4 11.0 0.47 12 PA
## 8 6.12 5.24 25 9 0.57083969 55 10 4 18.5 0.38 12 PA
## 9 3.29 15.79 43 12 1.45333122 50 4 4 7.5 0.95 12 PA
## 10 5.88 8.26 23 7 1.33106538 50 5 4 8.2 0.12 12 PA
Description:
We assign new names to the variables, to make them more comprehensible:
colnames(mydata) <- c("Rate", "HLenght", "AVGTraffic", "VOLTruck", "SignalsMi", "SpeedL", "HWidth", "Lane", "Access", "Intchg", "LWidth", "Htype")
head(mydata)
## Rate HLenght AVGTraffic VOLTruck SignalsMi SpeedL HWidth Lane Access Intchg LWidth Htype
## 1 4.58 4.99 69 8 0.20040080 55 10 8 4.6 1.20 12 FAI
## 2 2.86 16.11 73 8 0.06207325 60 10 4 4.4 1.43 12 FAI
## 3 3.02 9.75 49 10 0.10256410 60 10 4 4.7 1.54 12 FAI
## 4 2.29 10.65 61 13 0.09389671 65 10 6 3.8 0.94 12 FAI
## 5 1.61 20.01 28 12 0.04997501 70 10 4 2.2 0.65 12 FAI
## 6 6.87 5.97 30 6 2.00750419 55 10 4 24.8 0.34 12 PA
Now we can begin to analyze the data with the help of functions like stat.desc and summary:
round(stat.desc(mydata[ ,-12]), 2)
## Rate HLenght AVGTraffic VOLTruck SignalsMi SpeedL HWidth Lane Access Intchg LWidth
## nbr.val 39.00 39.00 39.00 39.00 39.00 39.00 39.00 39.00 39.00 39.00 39.00
## nbr.null 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 13.00 0.00
## nbr.na 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
## min 1.61 2.96 1.00 6.00 0.05 40.00 1.00 2.00 2.20 0.00 10.00
## max 9.23 40.09 73.00 15.00 2.79 70.00 10.00 8.00 53.00 1.54 13.00
## range 7.62 37.13 72.00 9.00 2.74 30.00 9.00 6.00 50.80 1.54 3.00
## sum 153.40 502.48 765.00 364.00 19.92 2145.00 268.00 122.00 474.20 11.56 466.00
## median 3.05 11.39 13.00 9.00 0.18 55.00 8.00 2.00 10.30 0.13 12.00
## mean 3.93 12.88 19.62 9.33 0.51 55.00 6.87 3.13 12.16 0.30 11.95
## SE.mean 0.32 1.22 2.98 0.38 0.11 0.94 0.49 0.22 1.49 0.07 0.07
## CI.mean.0.95 0.64 2.47 6.03 0.76 0.22 1.90 0.98 0.44 3.02 0.13 0.15
## var 3.94 57.91 346.40 5.54 0.44 34.21 9.22 1.85 86.83 0.17 0.21
## std.dev 1.99 7.61 18.61 2.35 0.66 5.85 3.04 1.36 9.32 0.41 0.46
## coef.var 0.50 0.59 0.95 0.25 1.30 0.11 0.44 0.43 0.77 1.39 0.04
summary(mydata)
## Rate HLenght AVGTraffic VOLTruck SignalsMi SpeedL HWidth
## Min. :1.610 Min. : 2.960 Min. : 1.00 Min. : 6.000 Min. :0.04545 Min. :40 Min. : 1.000
## 1st Qu.:2.630 1st Qu.: 7.995 1st Qu.: 5.00 1st Qu.: 8.000 1st Qu.:0.08738 1st Qu.:50 1st Qu.: 4.000
## Median :3.050 Median :11.390 Median :13.00 Median : 9.000 Median :0.17666 Median :55 Median : 8.000
## Mean :3.933 Mean :12.884 Mean :19.62 Mean : 9.333 Mean :0.51072 Mean :55 Mean : 6.872
## 3rd Qu.:4.595 3rd Qu.:17.800 3rd Qu.:24.00 3rd Qu.:11.000 3rd Qu.:0.71515 3rd Qu.:60 3rd Qu.:10.000
## Max. :9.230 Max. :40.090 Max. :73.00 Max. :15.000 Max. :2.78933 Max. :70 Max. :10.000
## Lane Access Intchg LWidth Htype
## Min. :2.000 Min. : 2.20 Min. :0.0000 Min. :10.00 FAI: 5
## 1st Qu.:2.000 1st Qu.: 6.95 1st Qu.:0.0000 1st Qu.:12.00 MA :13
## Median :2.000 Median :10.30 Median :0.1300 Median :12.00 MC : 2
## Mean :3.128 Mean :12.16 Mean :0.2964 Mean :11.95 PA :19
## 3rd Qu.:4.000 3rd Qu.:14.60 3rd Qu.:0.3600 3rd Qu.:12.00
## Max. :8.000 Max. :53.00 Max. :1.5400 Max. :13.00
From this data we can see that:
- 75% of highways have 4 or less
lanes of traffic, meanwhile the last 25% have more of 4 lanes of
traffic.
- The arithmetic mean of number of access point per mile
is: 12.16.
- The minimum width for the lanes is: 10 foot.
-
The maximum trucks volume of the total traffic volume is: 15%
We graph now the distribution of variables:
scatterplotMatrix(mydata[, -12],
smooth = FALSE)
hist(mydata$Rate,
xlab = "Rate per million vehicle miles",
ylab = "Frequency",
main = "Distribution of rate")
hist(mydata$HLenght,
xlab = "Miles",
ylab = "Frequency",
main = "length of the highway segment in miles")
hist(mydata$AVGTraffic,
xlab = "Traffic per thousands",
ylab = "Frequency",
main = "Average daily traffic")
hist(mydata$AVGTraffic,
xlab = "Traffic in thousands",
ylab = "Frequency",
main = "Total number of lanes of traffic")
We can see that most of this variables are asymmetrical to the right.
hist(mydata$SpeedL,
xlab = "Miles per hour",
ylab = "Frequency",
main = "Speed limits in 1973")
We can see that this variable is normally distributed.
A researcher examined the effects of online schooling on body weight
in ninth graders (Body mass.csv in Task 2 folder). 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.
1 Show the descriptive
statistics of body mass and its distribution with the histogram.
2
Test the following hypothesis with program R: 𝐻0: 𝜇 = 59.5.
3
Explain the results and interpret the effect size.
mydata2 <- read.table("/Users/eneaprelaz/Desktop/Bootcamp study material/R Take Home Exam/Task 2/Body mass.csv", header = TRUE, sep = ";", dec = ",")
head(mydata2, 6)
## 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
Description:
- Mass: Body weight in kg of ninth grader.
Descriptive statistic of body mass:
round(stat.desc(mydata2$Mass, 2))
## median mean SE.mean CI.mean.0.95 var std.dev coef.var
## 63 63 1 2 36 6 0
lower boundary: 63 - 2
upper boundary: 63 + 2
We now calculate the arithmetic mean and the standard error:
mean(mydata2$Mass)
## [1] 62.876
sd(mydata2$Mass) #standard deviation
## [1] 6.011403
We want to formulate our hypothesis:
H0 : µ = 59.5
H1 : µ != 59.5
And check the distribution of the variable with a histogram:
ggplot(mydata2, aes(x=Mass, )) +
geom_histogram(stat = "bin", position = "stack", binwidth = 5, fill = "blue", color = "white") +
ylab("Frequency") +
xlab("Mass in kg")
Testing the hypothesis with a t-test:
t.test(mydata2$Mass,
mu = 59.5,
alternative = "two.sided")
##
## One Sample t-test
##
## data: mydata2$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:
Estimated arithmetic mean is Y_hat = 62.9
We compare the p-value
to alfa = 0.05:
p-value < 0.001 < 0.05
We reject H0 at p < 0.001 and accept H1. The average ninth
graders’ weight of school year 2021/2022 is different from the average
ninth graders’ weight of school year 2018/2019. The average weight
increased.
95% CI for arithmetic mean: 61.2 < µ < 64.6
Because 59.5
is not included in the interval, we reject H0 at 5%.
We now calculate the effect size:
cohens_d(mydata2$Mass, mu = 59.5)
## Cohen's d | 95% CI
## ------------------------
## 0.56 | [0.26, 0.86]
##
## - Deviation from a difference of 59.5.
And interpret it:
interpret_cohens_d(0.56, rules = "sawilowsky2009")
## [1] "medium"
## (Rules: sawilowsky2009)
You analyze the price per m2 for a sample of apartments in the Ljubljana region (Apartments.xlsx in Task 3 folder). Follow the questions in R Markdown included in the folder.
mydata3 <- read_xlsx("~/Desktop/Bootcamp study material/R Take Home Exam/Task 3/Apartments.xlsx")
mydata3 <- as.data.frame(mydata3) #changing from tibble type to data frame
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:
mydata3$BalconyF <- factor(mydata3$Balcony,
levels = c (0, 1),
labels = c ("No", "Yes")) #Changing into factor the variable Balcony
mydata3$ParkingF <- factor(mydata3$Parking,
levels = c (0, 1),
labels = c ("No", "Yes")) #Changing into factor the variable Parking
summary(mydata3[, c (-4, -5)]) #Excluding the 4th and 5th column from the summary
## Age Distance Price BalconyF ParkingF
## Min. : 1.00 Min. : 1.00 Min. :1400 No :48 No :42
## 1st Qu.:12.00 1st Qu.: 4.00 1st Qu.:1710 Yes:37 Yes:43
## Median :18.00 Median :12.00 Median :1950
## Mean :18.55 Mean :14.22 Mean :2019
## 3rd Qu.:24.00 3rd Qu.:20.00 3rd Qu.:2290
## Max. :45.00 Max. :45.00 Max. :2820
Now let’s state our hypothesis:
H0 : Mu_Price = 1900
H1 : Mu_Price != 1900
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
Explanation:
Estimated arithmetic mean is Y_hat = 2019
We compare the p-value
to alfa = 0.05:
p-value: 0.004731 < 0.05
We reject H0 at p = 0.005 and accept H1. The average price per m2 is
different from 1900 Eur. The price increased.
95% CI for arithmetic mean: 1937 < Mu_Price < 2100
Because
1900 is not included in the interval, we reject H0 at 5%.
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
Explanation of the regression coefficient b1 = -8.975
If the age
of an apartment increases by 1 year, its price per m2 will decrease on
average by 9 eur.
Explanation of the coefficient of determination R^2 = 0.053
5.3%
of variability of the price per m2 can be explained by the age of the
apartment.
cor(mydata3$Price, mydata3$Age)
## [1] -0.230255
Explanation of the coefficient of correlation = -0.23
There is a
negative linear relationship between price per m2 and age.
scatterplotMatrix(mydata3[, c (-4, -5, -6, -7)],
smooth = FALSE)
Based on the scatter plot matrix there isn’t a multicolinearity problem.
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
vif(fit2) #Multicolinearity check
## Age Distance
## 1.001845 1.001845
mean(vif(fit2))
## [1] 1.001845
Neither age or distance should be removed based on the Variance
Inflation Factor < 5.
Also the mean of the VIFs of the variables
is very low, which also indicates that there isn’t a multicolinearity
problem.
Checking the standardized residuals:
mydata3$StdRes <- round(rstandard(fit2), 3) #Standardized residuals
ggplot(mydata3, aes(x =StdRes, )) +
geom_histogram(stat = "bin", position = "stack", binwidth = 0.2, fill = "orange", color = "red" ) +
ylab("Frequency") +
xlab("Standardized residuals")
shapiro.test(mydata3$StdRes)
##
## Shapiro-Wilk normality test
##
## data: mydata3$StdRes
## W = 0.95303, p-value = 0.003645
We order mydata3 with decreasing Standard Residuals and output the
first 3 rows:
head(mydata3[order(-mydata3$StdRes),], 3) #Three units with lowest value of stand. residuals
## Age Distance Price Parking Balcony BalconyF ParkingF StdRes
## 38 5 45 2180 1 1 Yes Yes 2.577
## 33 2 11 2790 1 0 No Yes 2.051
## 2 18 1 2800 1 0 No Yes 1.783
Checking the Cooks distances:
mydata3$CooksDis <- round(cooks.distance(fit2), 3) #Cooks distances
ggplot(mydata3, aes(x =CooksDis, )) +
geom_histogram(stat = "bin", position = "stack", binwidth = 0.025, fill = "purple", color = "white" ) +
ylab("Frequency") +
xlab("Cooks distance")
We order mydata3 with decreasing Cooks distance and output the first
3 rows:
head(mydata3[order(-mydata3$CooksDis),], 3) #Three units with highest value of Cooks distance
## Age Distance Price Parking Balcony BalconyF ParkingF StdRes CooksDis
## 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 No Yes 2.051 0.069
We found out that the row number 38 have the highest Cooks distance
of = 0.320. We need to remove this influential value.
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:pastecs':
##
## first, last
## The following object is masked from 'package:car':
##
## recode
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
mydata3 <- mydata3 %>%
filter(!CooksDis == 0.320) #Targeting only the influential unit with the exact Cooks distance of = 0.320
ggplot(mydata3, aes(x =StdRes, )) +
geom_histogram(stat = "bin", position = "stack", binwidth = 0.2, fill = "orange", color = "red" ) +
ylab("Frequency") +
xlab("Standardized residuals")
shapiro.test(mydata3$StdRes)
##
## Shapiro-Wilk normality test
##
## data: mydata3$StdRes
## W = 0.94879, p-value = 0.002187
ggplot(mydata3, aes(x =CooksDis, )) +
geom_histogram(stat = "bin", position = "stack", binwidth = 0.025, fill = "purple", color = "white" ) +
ylab("Frequency") +
xlab("Cooks distance")
And we run again the model without the influential value:
fit2 <- lm(Price ~ Age + Distance,
data = mydata3)
mydata3$StdFitted <- scale(fit2$fitted.values)
ggplot(mydata3, aes(x = StdFitted, y = StdRes)) +
geom_point() +
xlab("standardized Fitted values") +
ylab("standardized Residual") +
stat_smooth(method = "lm", formula = y ~ x, se = F)
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 = 2.927455
## Prob > Chi2 = 0.08708469
Doing this test we conclude that the Null hypothesis H0 cannot be rejected, so there isn’t a problem with Heteroskedasticity.
ggplot(mydata3, aes(x =StdRes, )) +
geom_histogram(stat = "bin", position = "stack", binwidth = 0.2, fill = "orange", color = "red" ) +
ylab("Frequency") +
xlab("Standardized residuals")
shapiro.test(mydata3$StdRes)
##
## Shapiro-Wilk normality test
##
## data: mydata3$StdRes
## W = 0.94879, p-value = 0.002187
H0 : Variable is normally distributed
H1 : Variable is NOT
normally distributed
We reject H0 at p-value = 0.003.
But since the sample size is
> 30 we can still assume it is normally distributed.
summary(fit2)
##
## Call:
## lm(formula = Price ~ Age + Distance, data = mydata3)
##
## 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
We cannot say that Age has statistically effect on Price per m2.
H0 : beta2 = 0
H1 : beta2 != 0
p-value < 0.001
Explanation of b2 = -23
If the distance from the city center
increases by 1 km, then the price per m2 decreases, on average, by 23
eur (p < 0.001), assuming that all other explanatory variables,
included in the model, are constant.
R^2 = 0.4838
The
48,38% of variability of price per m2 is explained by linear effect of
age and distance.
Test of significance of regression:
H0
: Ro2 = 0
H1 : Ro2 > 0
F = 37.96 and p-value <
0.001
We reject the 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 per m2 and explanatory
variables, included in the model.
sqrt(summary(fit2)$r.squared) #calculating the multiple correlation
## [1] 0.6955609
Multiple coefficient of correlation = 0.695
There is a
positive linear relationship between price per m2 and all two
explanatory variables, included in the model.
fit3 <- lm(Price ~ Age + Distance + ParkingF + BalconyF,
data = mydata3)
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 2 is better
H1 : model 3 is better
p = 0.03 <
0.05
We reject the null hypothesis at p = 0.03. The model 3 is
better, it explains more variability in price per m2.
summary(fit3)
##
## Call:
## lm(formula = Price ~ Age + Distance + ParkingF + BalconyF, data = mydata3)
##
## 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
We cannot say that having a balcony or age have statistically effect on price per m2.
H0 : beta3 = 0 H1 : beta3 != 0 p = 0.001
Given the age and distance, the apartments with parking cost on average 167.5 eur per m2 more than apartments without parking.
Test of significance of regression:
H0 : Ro2 = 0
H1 : Ro2
> 0
F = 22.04 and p-value < 0.001
We reject the
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 per m2 and explanatory variables, included in
the model.
mydata3$StdFitted <- round(fit3$fitted.values, 3)
mydata3$StdRes <- mydata3$Price - mydata3$StdFitted
head(mydata3[2, ])
## Age Distance Price Parking Balcony BalconyF ParkingF StdRes CooksDis StdFitted
## 2 18 1 2800 1 0 No Yes 427.803 0.03 2372.197
The residual for apartment ID2 = 427.803, meaning the model overestimated the price.