#install.packages("carData") #installing missing package
library(carData) #Activating package
mydata <- force(Wong) #Creating data frame
The data set, called Wong was taken from the carData package.
head(mydata) #Checking first 6 rows of mydata
## id days duration sex age piq viq
## 1 3358 30 4 Male 20.67077 87 89
## 2 3535 16 17 Male 55.28816 95 77
## 3 3547 40 1 Male 55.91513 95 116
## 4 3592 13 10 Male 61.66461 59 73
## 5 3728 19 6 Male 30.12731 67 73
## 6 3790 13 3 Male 57.06229 76 69
Explanation of data set:
After observing the data set, I noticed that the age has decimal places and in general when someone asks us for our age, we simply say the whole number. That is why I will be rounding down the age column (we do not say we are 24 years old when we are 23,6). Furthermore, I am not satisfied with the naming of the columns so I will also change those. Lastly, I added a “new” variable by converting the factors in Gender into vectors.
colnames(mydata)<- c("ID","Post_Coma","Coma","Gender","Age","Perf_IQ","Verb_IQ") #Renaming the columns
mydata$Age <- floor(mydata$Age) #Rounding down the age column
mydata$GenderN <- as.numeric(mydata$Gender) #Creating new column with numeric values of Gender
head(mydata,5)
## ID Post_Coma Coma Gender Age Perf_IQ Verb_IQ GenderN
## 1 3358 30 4 Male 20 87 89 2
## 2 3535 16 17 Male 55 95 77 2
## 3 3547 40 1 Male 55 95 116 2
## 4 3592 13 10 Male 61 59 73 2
## 5 3728 19 6 Male 30 67 73 2
Explanation of renamed data set:
Now that everything is easily readable, we have to do some descriptive statistics. I chose the function stat.desc because it gives the most information and rounded it for visibility. I also removed the ID and Gender columns as they either have no significance or no numerical data.
library(pastecs)
round(stat.desc(mydata[,c(-1,-4)]), 2)
## Post_Coma Coma Age Perf_IQ Verb_IQ GenderN
## nbr.val 331.00 331.00 331.00 331.00 331.00 331.00
## nbr.null 0.00 46.00 0.00 0.00 0.00 0.00
## nbr.na 0.00 0.00 0.00 0.00 0.00 0.00
## min 13.00 0.00 6.00 50.00 64.00 1.00
## max 11628.00 255.00 80.00 133.00 132.00 2.00
## range 11615.00 255.00 74.00 83.00 68.00 1.00
## sum 159493.00 4732.00 10380.00 28981.00 31433.00 591.00
## median 150.00 7.00 26.00 87.00 94.00 2.00
## mean 481.85 14.30 31.36 87.56 94.96 1.79
## SE.mean 62.50 1.43 0.76 0.83 0.77 0.02
## CI.mean.0.95 122.95 2.82 1.50 1.64 1.52 0.04
## var 1292958.09 678.08 192.28 228.96 197.49 0.17
## std.dev 1137.08 26.04 13.87 15.13 14.05 0.41
## coef.var 2.36 1.82 0.44 0.17 0.15 0.23
From this table we can gather a lot of information and I will explain some:
-Mean (Age) = 31.36; This tells us that the average age of the patients included in the study is 31.36 years. -Median (Coma) = 7; This tells us that 50% of the patients in the study was in a coma for less than or equal to 7 days while the other half was more than 7 days. -Range (PerfIQ) = 83; This tells us that the difference in performance IQ between the highest scoring patient in the study and the lowest was equal to 83.
mydata<-mydata[mydata$Coma != 0, ]
Removing the rows with null values in the “Coma” column because that column represents the number of days the patient was in a coma. If the amount is 0.00, it theoretically means that the person was in fact not in a coma and this research was about measuring the Recovery of IQ Post-Coma.
library(psych)
describeBy(mydata[,c(-1,-4,-8)],mydata$Gender) #Splitting data by gender
##
## Descriptive statistics by group
## group: Female
## vars n mean sd median trimmed mad min max range skew
## Post_Coma 1 63 319.51 453.89 135 218.61 131.95 18 2259 2241 2.28
## Coma 2 63 10.44 13.55 5 7.25 5.93 1 68 67 2.23
## Age 3 63 29.37 11.26 27 27.49 8.90 16 76 60 1.81
## Perf_IQ 4 63 87.90 18.13 86 86.57 17.79 50 133 83 0.57
## Verb_IQ 5 63 93.81 13.34 92 94.24 17.79 64 114 50 -0.14
## kurtosis se
## Post_Coma 5.22 57.18
## Coma 4.87 1.71
## Age 3.66 1.42
## Perf_IQ 0.08 2.28
## Verb_IQ -1.02 1.68
## ------------------------------------------------------------
## group: Male
## vars n mean sd median trimmed mad min max range skew
## Post_Coma 1 222 505.15 1148.86 164.5 249.08 178.65 13 11628 11615 5.89
## Coma 2 222 18.35 29.96 9.0 11.90 10.38 1 255 254 4.27
## Age 3 222 30.44 13.30 25.0 28.73 8.90 6 80 74 1.04
## Perf_IQ 4 222 87.80 14.41 87.0 87.53 14.83 50 130 80 0.19
## Verb_IQ 5 222 95.67 13.83 94.0 95.17 14.08 67 132 65 0.31
## kurtosis se
## Post_Coma 45.39 77.11
## Coma 23.21 2.01
## Age 0.27 0.89
## Perf_IQ -0.18 0.97
## Verb_IQ -0.49 0.93
As we can see gender does not play a huge role in this study and the data set has a lot more male patients than female so I will remove sex in further analysis.
library(car)
##
## Attaching package: 'car'
## The following object is masked from 'package:psych':
##
## logit
scatterplotMatrix(mydata[,c(-1,-4,-8)], #Scatterplot matrix
smooth = FALSE)
From this scatterplot matrix we can see some interesting trend-lines and correlations. As we could probably predict performance and verbal IQ have a positive linear correlation. This means that the higher performance IQ is, the higher the verbal IQ, and reversed.
Age affects both IQs only in the later years and seems to have a negative correlation with time spent in a coma. This means that the older people are, the less time they spend in a coma, which could possibly be explained by the physical vulnerability of elderly people. We cannot say that age affects number of days post coma at which IQ were measured because that was decided by the doctors/testers.
Number of days post coma the test was taken seems to have a positive correlation with both mathematical and verbal IQ, which means that the longer the patient is out of coma at the time of measurement, the higher the IQ scores are.
The “Coma” results are a bit off in my opinion. It shows a presumed negative correlation with performance IQ. This tells us that the less time the person spent in a coma the higher the performance IQ, but shows no correlation with verbal IQ.
mydata1 <- read.table("./Body mass.csv", #Creating data frame
header=TRUE,
sep = ";",
dec = ",")
head(mydata1, 3)
## ID Mass
## 1 1 62.1
## 2 2 64.5
## 3 3 56.5
Explanation of data set:
round(stat.desc(mydata1[,-1]),2) #Showing descriptive statistics and rounding for visibility
## nbr.val nbr.null nbr.na min max range
## 50.00 0.00 0.00 49.70 83.20 33.50
## sum median mean SE.mean CI.mean.0.95 var
## 3143.80 62.80 62.88 0.85 1.71 36.14
## std.dev coef.var
## 6.01 0.10
I also removed the first column as it gives us no additional information.
hist(mydata1$Mass,
main = "Distribution of body weight", #Distribution with histogram
ylab = "Frequency",
xlab = "Body weight")
We can see that the distribution is not completely normal as it has two peaks. This might be because of some early bloomers in the ninth grade.
t.test(mydata1$Mass,
mu = 59.5,
alternative = "two.sided")
##
## One Sample t-test
##
## data: mydata1$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
Explaining the results:
We reject null hypothesis at p<0.001 and accept H1. We can say that the average body weight of ninth graders in the school year 2021/2022 is not 59.5, therefore not the same as the average body weight of ninth graders in the school year 2018/2019. Their weight increased.
95% CI for arithmetic mean: 61.17 < Mu < 64.58. Because 59.5 is not included in the interval, we reject h0 at risk of 5%.
library(effectsize)
##
## Attaching package: 'effectsize'
## The following object is masked from 'package:psych':
##
## phi
cohens_d(mydata1$Mass, mu=59.5) #Calculating the effect size
## 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") #Interpreting the effect size
## [1] "medium"
## (Rules: sawilowsky2009)
library(readxl)
mydata3 <- read_xlsx("./Apartments.xlsx")
head(mydata3)
## # A tibble: 6 × 5
## Age Distance Price Parking Balcony
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 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$ParkingFactor <- factor(mydata3$Parking,
levels = c(0, 1),
labels = c("No", "Yes"))
mydata3$BalconyFactor <- factor(mydata3$Balcony,
levels = c(0, 1),
labels = c("No", "Yes"))
head(mydata3)
## # A tibble: 6 × 7
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor
## <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <fct>
## 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
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
Explaining the results:
Since p is not lower than 0.001, we have to compare it to alpha (0.05).
We reject null hypothesis at p = 0.005 because it is lower than alpha = 0.05 and accept H1. We can say that the average price per m2 of apartments in Ljubljana region is not 1900 €/m2.
95% CI for arithmetic mean: 1937 < Mu < 2101. In conclusion: Because 1900 is not included in the interval, we reject h0 at risk of 5%.
fit1 <- lm(Price ~ Age, #Dependent and explanatory variable
data = mydata3) #Name of the data frame
cor(mydata3$Price, mydata3$Age) #Calculating the coefficient of correlation
## [1] -0.230255
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
Explaining the results:
Regression model: Y = 2185.455 - 8.975*Age
We reject null hypothesis at p = 0.034, because it is lower than alpha = 0.05 and accept H1. We found out that age statistically affects price per m^2 of an apartment.
Estimate of regression coefficient b1 = -8.975 If age increases by one year, then the price per m^2 decreases by 8.975€ on average.
Pearson Correlation Coefficient r = -0.23 Tells us how strong and type (positive/negative) of linear correlation between the dependent variable and explanatory variable. There is a weak negative linear correlation between price and age.
Coefficient of Determination r^2 = 0.053 Tells us how much variability of the dependent variable is explained by the effect of explanatory variables. In our case, 5.3% of variability of price can be explained by the effect of age of an apartment.
library(car)
scatterplotMatrix(mydata3[,c(-4,-5,-6,-7)],
smooth = FALSE)
It looks like there is no multicollinearity while observing the correlation between age of the apartments and their distance from city center.
fit2 <- lm(Price ~ Age + Distance, #Dependent and explanatory variables
data = mydata3) #Name of the data frame
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
## Age Distance
## 1.001845 1.001845
It’s a very low multicollinearity (almost 1). It’s only a problem if it’s above 5.
mydata3$StdResid <- round(rstandard(fit2), 3) #Calculating Standardized residuals
hist(mydata3$StdResid,
xlab = "Standardized residuals",
ylab = "Frequency",
main = "Histogram of standardized residuals")
head(mydata3[order(mydata3$StdResid),], 3) #Three units with lowest value of stand. residuals
## # A tibble: 3 × 8
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor StdResid
## <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <fct> <dbl>
## 1 7 2 1760 0 1 No Yes -2.15
## 2 12 14 1650 0 1 No Yes -1.50
## 3 12 14 1650 0 0 No No -1.50
head(mydata3[order(-mydata3$StdResid),], 3) #Three units with highest value of stand. residuals
## # A tibble: 3 × 8
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor StdResid
## <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <fct> <dbl>
## 1 5 45 2180 1 1 Yes Yes 2.58
## 2 2 11 2790 1 0 Yes No 2.05
## 3 18 1 2800 1 0 Yes No 1.78
After calculating I used both a histogram and also, just in case, checked both 3 highest and lowest values of standardized residuals. I will not remove any units as they are not outliers (all between -3 and 3).
mydata3$CooksD <- round(cooks.distance(fit2), 3) #Calculating Cooks distances
hist(mydata3$CooksD,
xlab = "Cooks distance",
ylab = "Frequency",
main = "Histogram of Cooks distances")
head(mydata3[order(-mydata3$CooksD),], 3) #Three units with highest value of Cooks distance
## # A tibble: 3 × 9
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor StdResid
## <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <fct> <dbl>
## 1 5 45 2180 1 1 Yes Yes 2.58
## 2 43 37 1740 0 0 No No 1.44
## 3 2 11 2790 1 0 Yes No 2.05
## # ℹ 1 more variable: CooksD <dbl>
After examining the histogram we can see that no values exceed Cooks distance 1 but there is one that stands out by a lot. We tracked it down by checking the 3 units with the highest Cooks Distance. We will remove it in the next step.
mydata3 <- mydata3[-38, ] #Removing the most influential value
fit2 <- lm(Price ~ Age + Distance,
data = mydata3) #I have to use it here otherwise the next code doesn't work
mydata3$StdFitted <- scale(fit2$fitted.values)
library(car)
scatterplot(y = mydata3$StdResid, x = mydata3$StdFitted,
ylab = "Standardized residuals",
xlab = "Standardized fitted values",
boxplots = FALSE,
regLine = FALSE,
smooth = FALSE)
I assume there is a small heteroskedasticity from left to right (left side all values above -1 and the right side has even below -2). This means that the standard errors are biased —> We cannot trust t-test for regression coefficient.
I decided to test this theory with the Breusch Pagan heteroskedasticity test:
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
p = 0.087, which is more than alpha = 0.05. We cannot reject the null hypothesis, so we will assume there is homoskedasticity.
hist(mydata3$StdResid,
xlab = "Standardized residuals",
ylab = "Frequency",
main = "Histogram of standardized residuals")
shapiro.test(mydata3$StdResid)
##
## Shapiro-Wilk normality test
##
## data: mydata3$StdResid
## W = 0.94879, p-value = 0.002187
Explaining the findings:
p = 0.0022 which is less than alpha = 0.05. We reject the null hypothesis at p = 0.0022 and accept H1. We will assume that the variable is not normally distributed, but this does not affect us because there are more than 30 observed units.
fit2 <- lm(Price ~ Age + Distance,
data = mydata3) #I already did it before this is just for visibility
sqrt(summary(fit1)$r.squared) #Coefficient of multiple correlation
## [1] 0.230255
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
Explanation of all coefficients:
Regression model: Price per m2 = 2456.08 - 6.46Age - 22.96Distance
Explaining b1 = -6.46: If the average age of an apartment increases by 1 year, then the price per m2 on average decreases by 6.46€ (p=0.044), assuming all other explanatory variables included in the model are constant.
Explanation of b2 = -22.96 If the average distance from the city center increases by 1 km, then the price per m2 on average decreases by 22.96€ (p<0.001), assuming that all other explanatory variables included in the model are constant.
Multiple-R^2 = 0.4838 48.38% of variability of Price is explained by Age and Distance.
We reject null hypothesis at p<0.001. We can say that the coefficient of determination is more than 0, meaning that we found linear relationship between Price and explanatory variables included in the model.
Multiple coefficient of correlation = 0.230255 There is a weak linear relationship between Price and both explanatory variables included in the model.
fit3 <- lm(Price ~ Age + Distance + ParkingFactor + BalconyFactor,
data = mydata3)
summary(fit3)
##
## Call:
## lm(formula = Price ~ Age + Distance + ParkingFactor + BalconyFactor,
## 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 ***
## ParkingFactorYes 167.531 62.864 2.665 0.00933 **
## BalconyFactorYes -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
anova(fit2, fit3) #Comparison of two regression models that differ in the number of expl. variables
## Analysis of Variance Table
##
## Model 1: Price ~ Age + Distance
## Model 2: Price ~ Age + Distance + ParkingFactor + BalconyFactor
## 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
We reject the null hypothesis at p = 0.031 < alpha = 0.05. Model 2 is better as it explains more variability in Price.
summary(fit3)
##
## Call:
## lm(formula = Price ~ Age + Distance + ParkingFactor + BalconyFactor,
## 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 ***
## ParkingFactorYes 167.531 62.864 2.665 0.00933 **
## BalconyFactorYes -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
Explaining regression coefficients for categorical variables:
Explaining b3 = 167.53
Assuming that all other variables are the same, then the apartments with parking are on average 167.53€/m^2 more expensive compared to apartments without parking (p=0.010).
We cannot say that Balcony has statistical effect on Price (p=0.798).
F-statistics:
Explanation: In multiple regression, the F-statistic tests all independent variables as a group (b1 = b1 + b2 + b3 + b4).
mydata3$Fitted <- fitted.values(fit3) #Saving fitted values
mydata3$Residuals <- residuals(fit3) #Calculating the residuals
mydata3$Residuals[2] #Showing the residual for apartment ID2
## 2
## 427.8029