data()
data(package = .packages(all.available = TRUE))
#install.packages("carData")
library(carData)
mydata <- force(Davis)
head(mydata)
## sex weight height repwt repht
## 1 M 77 182 77 180
## 2 F 58 161 51 159
## 3 F 53 161 54 158
## 4 M 68 177 70 175
## 5 F 59 157 59 155
## 6 M 76 170 76 165
Explanation of dataset:
Renaming the columns of the “mydata” dataset to “Gender,” “Weight,” “Height,” “ReportedW,” and “ReportedH.
colnames(mydata) <- c ("Gender" , "Weight" , "Height" , "ReportedW" , "ReportedH")
head(mydata)
## Gender Weight Height ReportedW ReportedH
## 1 M 77 182 77 180
## 2 F 58 161 51 159
## 3 F 53 161 54 158
## 4 M 68 177 70 175
## 5 F 59 157 59 155
## 6 M 76 170 76 165
mydata2 <- mydata [mydata$Gender== "F", ]
mydata$IncreasedW<- mydata$Weight +3
head(mydata)
## Gender Weight Height ReportedW ReportedH IncreasedW
## 1 M 77 182 77 180 80
## 2 F 58 161 51 159 61
## 3 F 53 161 54 158 56
## 4 M 68 177 70 175 71
## 5 F 59 157 59 155 62
## 6 M 76 170 76 165 79
mydata3 <- mydata[mydata$Height >= 170 & mydata$Height <= 180, ]
head(mydata3)
## Gender Weight Height ReportedW ReportedH IncreasedW
## 4 M 68 177 70 175 71
## 6 M 76 170 76 165 79
## 9 M 71 178 71 175 74
## 10 M 65 171 64 170 68
## 11 M 70 175 75 174 73
## 20 F 61 175 61 171 64
summary(mydata[ , c(2,3)])
## Weight Height
## Min. : 39.0 Min. : 57.0
## 1st Qu.: 55.0 1st Qu.:164.0
## Median : 63.0 Median :169.5
## Mean : 65.8 Mean :170.0
## 3rd Qu.: 74.0 3rd Qu.:177.2
## Max. :166.0 Max. :197.0
Generating a detailed statistical description of the variables in the “mydata” dataset.
library(psych)
describe(mydata)
## vars n mean sd median trimmed mad min max range
## Gender* 1 200 1.44 0.50 1.0 1.43 0.00 1 2 1
## Weight 2 200 65.80 15.10 63.0 64.21 11.86 39 166 127
## Height 3 200 170.02 12.01 169.5 170.32 9.64 57 197 140
## ReportedW 4 183 65.62 13.78 63.0 64.27 11.86 41 124 83
## ReportedH 5 183 168.50 9.47 168.0 168.19 10.38 148 200 52
## IncreasedW 6 200 68.80 15.10 66.0 67.21 11.86 42 169 127
## skew kurtosis se
## Gender* 0.24 -1.95 0.04
## Weight 2.01 8.96 1.07
## Height -4.00 37.07 0.85
## ReportedW 1.03 1.33 1.02
## ReportedH 0.33 -0.36 0.70
## IncreasedW 2.01 8.96 1.07
Standard deviation for Reportedw= 13.78 indicates a measure of the dispersion or variability within the data, with values spread around the mean by approximately 13.78 units on average.
library(psych)
describeBy(mydata$Weight, mydata$Gender)
##
## Descriptive statistics by group
## group: F
## vars n mean sd median trimmed mad min max range skew
## X1 1 112 57.87 12.38 56 56.76 5.93 39 166 127 5.94
## kurtosis se
## X1 49.24 1.17
## ----------------------------------------------------
## group: M
## vars n mean sd median trimmed mad min max range skew
## X1 1 88 75.9 11.89 75 75.1 11.86 54 119 65 0.78
## kurtosis se
## X1 0.88 1.27
Explaining data by genders: - Average weight for females is 57.87 - Average weight for males is 75.9
boxplot(mydata[, c(2, 3)], col = "blue")
Based on boxplot we can see that both variables have outlires. Weight has outlier above maximum value while height has outlier bellow minimum value.
hist (mydata$ReportedW,
main = "Distribution of weight of subjects",
xlab = "Measured weight",
breaks = seq(from = 0, to =150, by= 5),
col= "green" ,
border= "yellow")
Based on this histogram , we can see that distribution is relatively normal with slight right skewness. It means that the majority of data points are clustered around the mean, but there is a slight elongation of the tail to the right, indicating some moderately higher values in the data.
Bodymass <- read.table("~/R Take Home Exam/Task 2/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
mean(Bodymass$Mass)
## [1] 62.876
sd(Bodymass$Mass)
## [1] 6.011403
hist(Bodymass$Mass,
main = "Bodymass distribution",
xlab = "Bodymass of students")
𝐻0: 𝜇 = 59.5 H1: 𝜇 is not equal to 59.5
t.test(Bodymass$Mass,
mu = 59.5,
alternative ="two.sided")
##
## 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
The one-sample t-test results show a statistically significant distinction among the sample mean (62.876 kg) and the hypothesized population mean (59.5 kg), with a p-value of 0.0009995, indicating that the average body mass of ninth graders is greater than 59.5 kg. As a result, we reject Ho and accept H1. The real population mean body mass is likely bigger than the estimated 59.5 kg, as seen by the 95% confidence interval [61.17, 64.58] kg, which expresses our confidence that it falls within this range.
library(effectsize)
##
## Attaching package: 'effectsize'
## The following object is masked from 'package:psych':
##
## phi
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.
interpret_cohens_d(0.5, rules = "sawilowsky2009")
## [1] "medium"
## (Rules: sawilowsky2009)
According to sawilowsky2009, there was a medium change in mass.
library(readxl)
ApartmentsData <- read_xlsx("~/R Take Home Exam/Task 3/Apartments.xlsx")
ApartmentsData <- as.data.frame(ApartmentsData)
head(ApartmentsData)
## 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:
ApartmentsData$ParkingFactor <- factor(ApartmentsData$Parking,
levels = c(0, 1),
labels = c("No", "Yes"))
ApartmentsData$BalconyFactor <- factor(ApartmentsData$Balcony,
levels = c(0, 1),
labels = c("No", "Yes"))
head(ApartmentsData, 3)
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor
## 1 7 28 1640 0 1 No Yes
## 2 18 1 2800 1 0 Yes No
## 3 7 28 1660 0 0 No No
t.test(ApartmentsData$Price,
paired = FALSE,
mu = 1900,
alternative ="two.sided")
##
## One Sample t-test
##
## data: ApartmentsData$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
Based on the reported p-value of 0.004731, which is less than the typical significance level of 0.05, we may infer that there is strong statistical evidence to reject the null hypothesis, suggesting that the real mean apartment price is not equal to 1900 and is most likely greater.
fit1 <- lm(Price ~ Age,
data = ApartmentsData)
summary(fit1)
##
## Call:
## lm(formula = Price ~ Age, data = ApartmentsData)
##
## 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(ApartmentsData$Price, ApartmentsData$Age)
## [1] -0.230255
library(car)
##
## Attaching package: 'car'
## The following object is masked from 'package:psych':
##
## logit
scatterplot(ApartmentsData$Price ~ ApartmentsData$Age,
ylab = "Price per m^2",
xlab = "Apartment Age",
smooth = FALSE,
boxplots = FALSE,
col = "blue",
data = ApartmentsData)
Estimate of the Regression Coefficient: In a linear regression model, the number 2185.46 reflects the estimated intercept of the mean price per square meter for properties at age 0. When age is not a consideration, this represents the beginning price per square meter.
The Age coefficient (-8.975) indicates that the price is expected to decline by around 8.975 units for each additional year of age.
Coefficient of Correlation: The correlation value of -0.23 indicates a modest negative correlation among age and price, meaning that as age increases, price tends to fall somewhat, although the relationship is not significant.
Coefficient of determination: Squared value of 0.053 indicates that age accounts for just 5.3% of the price per square meter variability, implying that age has a minimal influence on price changes.
library(car)
scatterplotMatrix(ApartmentsData[ , c(-4,-5,-6,-7)],
smooth = FALSE)
library(Hmisc)
##
## Attaching package: 'Hmisc'
## The following object is masked from 'package:psych':
##
## describe
## The following objects are masked from 'package:base':
##
## format.pval, units
rcorr(as.matrix(ApartmentsData[ , c(-4, -5, -6, -7)]))
## 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
The scatterplot matrix, which depicts the associations between Price, Age, and Distance, displays very minor correlations. The correlation coefficient between age and distance, in particular, is basically 0.04. Because of the low correlation, there is no evidence of considerable multicollinearity between these two explanatory factors. As a result, a multicollinearity test may not be required.
fit2 <- lm(Price ~ Age + Distance,
data = ApartmentsData)
summary(fit2)
##
## Call:
## lm(formula = Price ~ Age + Distance, data = ApartmentsData)
##
## 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)
## Age Distance
## 1.001845 1.001845
Both age and distance have VIF values of about 1.001845, suggesting extremely low multicollinearity. This suggests that the variables’ strong correlation poses no significant problem, allowing for meaningful interpretation of their effects in the regression model.
ApartmentsData$StdResid <- round(rstandard(fit2), 5)
ApartmentsData$CooksD <- round(cooks.distance(fit2), 5)
hist(ApartmentsData$StdResid ,
xlab = "Standardized residuals" ,
ylab= "Frequency",
main = "Histogram of standardized residuals",
breaks = seq ( from = -3, to = 3, by = 0.5 ) ,
col = "yellow" ,
border = "blue")
hist(ApartmentsData$CooksD,
xlab = "Cooks distance",
ylab = "Frequency",
main = "Cooks distances Histogram")
head(ApartmentsData[order(-ApartmentsData$CooksD),], 6) #Six units with lowest value of stand. residuals
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor
## 38 5 45 2180 1 1 Yes Yes
## 55 43 37 1740 0 0 No No
## 33 2 11 2790 1 0 Yes No
## 53 7 2 1760 0 1 No Yes
## 22 37 3 2540 1 1 Yes Yes
## 39 40 2 2400 0 1 No Yes
## StdResid CooksD
## 38 2.57677 0.31973
## 55 1.44477 0.10420
## 33 2.05059 0.06913
## 53 -2.15179 0.06626
## 22 1.57598 0.06087
## 39 1.09118 0.03751
Since none of the values in the distribution of standardised residuals, as visually represented, exceed an absolute value of 3 or fall below -3, there is no requirement to eliminate additional data points.When compared to the rest of the dataset, observations associated with ID 38 and ID 55 had considerably greater Cook’s Distance values of 0.32 and 0.10, respectively. These outliers should be removed because they have a significant impact on the analysis.
Although the majority of Cook’s distances are less than 0.15, there is an obvious outlier(s) with a bigger influence, lying between 0.30 and 0.35, that warrants further examination and possible removal.
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:Hmisc':
##
## src, summarize
## 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
ApartmentsData <- ApartmentsData %>%
filter(!(Price %in% c("2180", "1740"))) #Filter out influencing values
hist(ApartmentsData$CooksD,
xlab = "Cooks distance",
ylab = "Frequency",
main = "Cooks distances Histogram")
Three potential outliers with Cook’s values of 0.6 will be retained in the analysis because removing them is unnecessary and would reduce data analysis precision.
fit2 <- lm(Price ~ Age + Distance,
data = ApartmentsData)
ApartmentsData$StdFitted <- scale(fit2$fitted.values)
library(car)
scatterplot(y = ApartmentsData$StdResid, x = ApartmentsData$StdFitted,
ylab = "Standardized residuals",
xlab = "Standardized fitted values",
boxplots = FALSE,
regLine = TRUE,
smooth = FALSE)
The scatterplot shows potential nonlinearity and heteroskedasticity, but because these concerns were not observed previous, we won’t linger on them. A Breusch-Pagan test should be used to confirm heteroskedasticity.
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
We will not reject the null hypothesis (Ho) suggesting constant variance (homoskedasticity) with a p-value of 0.052 (5.2%), which is slightly higher than the 5% criterion. This implies that our data does not exhibit considerable heteroskedasticity.
hist(ApartmentsData$StdResid,
xlab = "Standardized residuals",
ylab = "Frequency",
main = "Histogram of Standardized Residuals",
col = "yellow",
border= "green" )
shapiro.test(ApartmentsData$StdResid)
##
## Shapiro-Wilk normality test
##
## data: ApartmentsData$StdResid
## W = 0.94966, p-value = 0.002646
The data exhibits a right-skewed normal distribution. We conducted a Shapiro-Wilk test to assess this assumption.
Null Hypothesis (H0): The data is normally distributed. Alternative Hypothesis (H1): The data is not normally distributed.
With a significance level (p-value) of 0.002, which is below the 0.05 threshold, we find compelling evidence to reject the null hypothesis. Therefore, we accept the alternative hypothesis, indicating that the data is not normally distributed.
summary(fit2)
##
## Call:
## lm(formula = Price ~ Age + Distance, data = ApartmentsData)
##
## 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
The revised model shows some changes in coefficients: the intercept is now 2490.1EUR, age still has an average decrease of 7.9EUR per m2 for each year (p=0.02), and distance from the center decreases the price by 23.9EUR per m2 (p<0.001). The R-squared increased to 49.68%, meaning these variables explain 49.68% of price variability. Both age and distance remain statistically significant (p<0.05), indicating their impact on price per m2.
fit3 <- lm(Price ~ Age + Distance + ParkingFactor + BalconyFactor,
data = ApartmentsData)
anova(fit2, fit3)
## 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 80 5982100
## 2 78 5458696 2 523404 3.7395 0.02813 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
H0 = fit2 is better H1 = fit3 is better
The ANOVA test with a significance level of 0.02813 suggests that model fit3 (Price ~ Age + Distance + ParkingFactor + BalconyFactor) fits the data better than fit2 (Price ~ Age + Distance).
summary(fit3)
##
## Call:
## lm(formula = Price ~ Age + Distance + ParkingFactor + BalconyFactor,
## data = ApartmentsData)
##
## 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 ***
## ParkingFactorYes 168.921 62.166 2.717 0.00811 **
## BalconyFactorYes -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
Important findings:
Significant (p=0.03): Age. A one-year increase in apartment age corresponds to a 7.2EUR drop in price per m2.
Significant distance (p0.001). A one-kilometer increase in distance from the city center results in a 21.2EUR fall in price per m2.
Parking (p=0.008): This is significant. Apartments with parking cost 168.92EUR more per m2.
Balcony (p=0.9): Not statistically significant.
The F-statistic (p=0.001) indicates that the price and variables have a linear connection. The balcony has no effect.
ApartmentsData$Fitted <- fitted.values(fit3)
ApartmentsData$Residuals <- residuals(fit3)
head(ApartmentsData[colnames(ApartmentsData) %in% c("Price", "Fitted", "Residuals")], 2)
## Price Fitted Residuals
## 1 1640 1706.795 -66.79523
## 2 2800 2377.043 422.95718
Apartment ID2’s actual price per m2 is 2800EUR, while our model’s predicted value is 2377.04EUR. This results in a residual (difference) of 422.96EUR per m2.