Kaggle; Water Quality, Drinking water probability, accessed on 22th of September on link: https://www.kaggle.com/datasets/adityakadiwal/water-potability
Content The water_potability.csv file contains water quality metrics for 3276 different water bodies.
mydata <- read.table("./water_potability.csv", header = TRUE, sep = ",", dec= ".")
head(mydata)
## ph Hardness Solids Chloramines Sulfate Conductivity
## 1 NA 204.8905 20791.32 7.300212 368.5164 564.3087
## 2 3.716080 129.4229 18630.06 6.635246 NA 592.8854
## 3 8.099124 224.2363 19909.54 9.275884 NA 418.6062
## 4 8.316766 214.3734 22018.42 8.059332 356.8861 363.2665
## 5 9.092223 181.1015 17978.99 6.546600 310.1357 398.4108
## 6 5.584087 188.3133 28748.69 7.544869 326.6784 280.4679
## Organic_carbon Trihalomethanes Turbidity Potability
## 1 10.379783 86.99097 2.963135 0
## 2 15.180013 56.32908 4.500656 0
## 3 16.868637 66.42009 3.055934 0
## 4 18.436524 100.34167 4.628771 0
## 5 11.558279 31.99799 4.075075 0
## 6 8.399735 54.91786 2.559708 0
1.Explanation of dataset:
ppm: parts per million
2.Data manipulation:
I extracted variables that I will not be using in my analysis and created new data frame:
mydata2 <- mydata[,c(1,2,3,10)]
head(mydata2)
## ph Hardness Solids Potability
## 1 NA 204.8905 20791.32 0
## 2 3.716080 129.4229 18630.06 0
## 3 8.099124 224.2363 19909.54 0
## 4 8.316766 214.3734 22018.42 0
## 5 9.092223 181.1015 17978.99 0
## 6 5.584087 188.3133 28748.69 0
I found rows with incomplete data and extracted it from the case. Now I have data frame Mydata3 that only includes observations with complete data:
#install.packages(pastecs)
library(tidyr)
mydata3 <- drop_na(mydata2)
mydata3 <- round(mydata3, 2)
Showing only 10 observations from 2785 for mydaat3:
head(mydata3, 10)
## ph Hardness Solids Potability
## 1 3.72 129.42 18630.06 0
## 2 8.10 224.24 19909.54 0
## 3 8.32 214.37 22018.42 0
## 4 9.09 181.10 17978.99 0
## 5 5.58 188.31 28748.69 0
## 6 10.22 248.07 28749.72 0
## 7 8.64 203.36 13672.09 0
## 8 11.18 227.23 25484.51 0
## 9 7.36 165.52 32452.61 0
## 10 7.97 218.69 18767.66 0
Changing categorical variables to factors:
mydata3$PotabilityP <- factor(mydata3$Potability,
levels = c(1, 0),
labels = c("Potable", "Not potable"))
3.Descriptive statistics:
summary(mydata3)
## ph Hardness Solids Potability
## Min. : 0.000 Min. : 47.43 Min. : 320.9 Min. :0.0000
## 1st Qu.: 6.090 1st Qu.:176.84 1st Qu.:15661.9 1st Qu.:0.0000
## Median : 7.040 Median :197.08 Median :20868.6 Median :0.0000
## Mean : 7.081 Mean :196.28 Mean :21971.0 Mean :0.3953
## 3rd Qu.: 8.060 3rd Qu.:216.62 3rd Qu.:27317.1 3rd Qu.:1.0000
## Max. :14.000 Max. :323.12 Max. :56867.9 Max. :1.0000
## PotabilityP
## Potable :1101
## Not potable:1684
##
##
##
##
Mean for ph: The avarage ph in our water body sample is 7.081 ph.
Median for Hardness: 50% of the water bodies have hardness 197.08 mg/L or less and the other 50% have hardness more than 197.0 mg/L.
Max.for Solids: The most solids dissolved in our sample is 56867.9 ppm.
4.Graphs:
Histogram for ph:
colors <- c("red","darkorange", "orange", "yellow", "darkseagreen1", "palegreen", "palegreen2", "palegreen3", "lightseagreen", "lightskyblue", "blue", "darkorchid2", "darkorchid3", "darkorchid4")
hist(mydata3$ph,
main = "Distribution of pH of water",
xlab = "pH",
ylab = "Frequency",
col = colors,
breaks = seq(from = 0, to = 14, by = 1))
Graph is normally distributed. The most values have ph between 6 and 8.
Histogram for Hardness:
hist(mydata3$Hardness,
main = "Distribution of Hardness of water",
xlab = "Hardness",
ylab = "Frequency",
col = "lightskyblue",
breaks = seq(from = 0, to = 400, by = 10))
Graph is normally distributed.
Boxplot for Solids:
boxplot(mydata3$Solids)
Minimum is 320.9 Maximum is 56867.9 range is: max - min. = 56867.9 - 320.9 = 56.547
First (1st Qu.:15661.9) and third (3rd Qu.:27317.1 ) quartile make the grey box. Median (the bold line): 20868.6
This are the outliers at the top:
head(mydata3[order(-mydata3$Solids), ],11)
## ph Hardness Solids Potability PotabilityP
## 877 5.38 153.71 56867.86 0 Not potable
## 1327 8.94 215.67 56488.67 1 Potable
## 1006 9.48 122.91 56351.40 1 Potable
## 2670 6.56 241.29 56320.59 1 Potable
## 910 3.34 156.48 55334.70 0 Not potable
## 2681 9.08 222.04 53735.90 1 Potable
## 312 4.04 291.46 52318.92 1 Potable
## 2740 7.87 210.63 51731.82 1 Potable
## 2653 8.14 153.75 50793.90 1 Potable
## 1519 9.25 168.04 50279.26 0 Not potable
## 2708 9.29 193.06 50166.53 1 Potable
mydata <- read.table("./Body mass.csv",
header=TRUE,
sep=";",
dec=",")
head(mydata)
## 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
1. Description of the variables
ID: identification number of each student in year 2021/2022 Mass: body mass of each student in kg in year 2021/2022
summary(mydata$Mass)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 49.70 60.23 62.80 62.88 64.50 83.20
Explanation of parameters:
Min. = 49.70: the minimum Mass of the students in the sample is 49.70 kg in year 2021/2022. Median = 62.80: 50% of students in our sample have body mass 62.88 or less, and the other 50% have more than that. Mean = 62.88: the avarage body mass of the students in the sample is 62.88 kg.
Histogram
hist(mydata$Mass,
main = "Distribution of the variable Mass",
ylab = "Frequency",
xlab = "Mass",
breaks = seq(30,100,10),
right = FALSE,
col="pink",
border = "white")
Mean for Mass calculated again:
mean(mydata$Mass)
## [1] 62.876
2. Hypothesis test of two arithmetic means
t- test
H0: Mu = 59.5 kg H1: Mu =/ 59.5 kg #TWO SIDED
t.test(mydata$Mass,
mu = 59.5,
alternative = "two.sided")
##
## One Sample t-test
##
## data: mydata$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
3. Results and effect size
Estimate of arithmetic mean: y_hat = 62.876
p here is 0.000234 which is much less than 0.05 –> we reject H0. There is 0.0002 probability that the price is still the same.
Conclusion: We reject H0 at p < 0.001 and accept H1. Average Mass in the year 2021/22 is different than it was in year 2018/19. The mass increased.
95% confidence interval for arithmetic mean is 61.17 < Mu < 64.6 Because 59,5 kg isn’t included in the interval we reject H0 at 5%.
Effect size
#install.packages("effectsize")
library(effectsize)
cohens_d(mydata$Mass, mu = 59.5)
## Cohen's d | 95% CI
## ------------------------
## 0.56 | [0.26, 0.86]
##
## - Deviation from a difference of 59.5.
Sawilowsky 2009 interpretation
interpret_cohens_d(0.56, rules = "sawilowsky2009" )
## [1] "medium"
## (Rules: sawilowsky2009)
#install.packages(pastecs)
library(pastecs)
##
## Attaching package: 'pastecs'
## The following object is masked from 'package:tidyr':
##
## extract
round(stat.desc(mydata$Mass), 2)
## nbr.val nbr.null nbr.na min max
## 50.00 0.00 0.00 49.70 83.20
## range sum median mean SE.mean
## 33.50 3143.80 62.80 62.88 0.85
## CI.mean.0.95 var std.dev coef.var
## 1.71 36.14 6.01 0.10
confidence interval: lower boundary: 62.88 - 1.71 upper boundary: 62.88 + 1.71 (mean +- CI.mean)
Instructions: You analyze the price per m2 for a sample of apartments in the Ljubljana region. Follow the instructions bellow:
1. Import the dataset Apartments.xlsx
#install.packages("readxl")
library(readxl)
mydata <- read_xlsx("./Apartments.xlsx")
mydata <- as.data.frame(mydata) #instead of tibble, we use data.frame (df) option
head(mydata)
## 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:
2. Change categorical variables into factors.
mydata$BalconyN <- factor(mydata$Balcony,
levels = c(0,1),
labels = c ("No", "Yes"))
head(mydata)
## Age Distance Price Parking Balcony BalconyN
## 1 7 28 1640 0 1 Yes
## 2 18 1 2800 1 0 No
## 3 7 28 1660 0 0 No
## 4 28 29 1850 0 1 Yes
## 5 18 18 1640 1 1 Yes
## 6 28 12 1770 0 1 Yes
mydata$ParkingN <- factor(mydata$Parking,
levels = c(0,1),
labels = c ("No", "Yes"))
head(mydata)
## Age Distance Price Parking Balcony BalconyN ParkingN
## 1 7 28 1640 0 1 Yes No
## 2 18 1 2800 1 0 No Yes
## 3 7 28 1660 0 0 No No
## 4 28 29 1850 0 1 Yes No
## 5 18 18 1640 1 1 Yes Yes
## 6 28 12 1770 0 1 Yes No
mean(mydata$Price)
## [1] 2018.941
#install.packages("pastecs")
library(pastecs)
round(stat.desc(mydata),2)
## Age Distance Price Parking Balcony BalconyN
## nbr.val 85.00 85.00 85.00 85.00 85.00 NA
## nbr.null 0.00 0.00 0.00 42.00 48.00 NA
## nbr.na 0.00 0.00 0.00 0.00 0.00 NA
## min 1.00 1.00 1400.00 0.00 0.00 NA
## max 45.00 45.00 2820.00 1.00 1.00 NA
## range 44.00 44.00 1420.00 1.00 1.00 NA
## sum 1577.00 1209.00 171610.00 43.00 37.00 NA
## median 18.00 12.00 1950.00 1.00 0.00 NA
## mean 18.55 14.22 2018.94 0.51 0.44 NA
## SE.mean 1.05 1.23 40.98 0.05 0.05 NA
## CI.mean.0.95 2.09 2.45 81.50 0.11 0.11 NA
## var 93.96 129.44 142764.34 0.25 0.25 NA
## std.dev 9.69 11.38 377.84 0.50 0.50 NA
## coef.var 0.52 0.80 0.19 0.99 1.15 NA
## ParkingN
## nbr.val NA
## nbr.null NA
## nbr.na NA
## min NA
## max NA
## range NA
## sum NA
## median NA
## mean NA
## SE.mean NA
## CI.mean.0.95 NA
## var NA
## std.dev NA
## coef.var NA
Explanation of parameters:
max. = 45.00 The highest age of the apartment in Ljubljana in our sample is 45.00 years.
Range for distance is 45 - 1 = 44 km. The difference between the furthest and the closest apartment from the city center is 44km.
mean = 2018.94 An apartment in Ljubljana in our sample costs on average 2018.94 euros per m2.
3.Test the hypothesis H0: Mu_Price = 1900 eur. What can you conclude?
My hypothesis: H0: Mu_price = 1900 eur H1: Mu_price != 1900 eur #not euqal to 1900 eur
t.test(mydata$Price,
mu = 1900,
alternative = "two.sided")
##
## One Sample t-test
##
## data: mydata$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
Estimate of arithmetic mean: y_hat = 2018.941
We check the p-value, which we compare to alfa (usually 5%). >>> P -value is here 0.004731, which is less than 0.05 (or 5%). We can reject H0.
Conclusion: We reject H0 at p < 0.05 and accept H1. Average price of the apartment in Ljubljana is different than 1900. 95% confidence interval for arithmetic mean is 1937.443 < Mu < 2100.440.
4. Estimate the simple regression function: Price = f(Age). Save results in object fit1 and explain the estimate of regression coefficient, coefficient of correlation and coefficient of determination.
#install.packages(car)
library(car)
## Loading required package: carData
scatterplot(mydata$Price ~ mydata$Age,
smooth = FALSE,
boxplots = FALSE,
ylab = "Price in euros",
xlab = "Age in years")
Now we would like to write it as a function:
fit <- lm(Price ~ Age,
data = mydata)
summary(fit)
##
## Call:
## lm(formula = Price ~ Age, data = mydata)
##
## 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
Price_hat = 2185.455 - 8.975 Age If age increases by 1 year, then the price decreases for 8.975 euros on average.
We make hypothesis:
H0: Beta1 = 0 #the function would be horizontal - age doesn’t affect price of the apartment H1: Beta1 != 0 #age affects the price
We check the p-value: p= 0.034 (< 0.05)
Conclusion: We rejected H0 at p = 0.05. We assume that age statistically affects price.
Explanations:
b1 = -8.975 If age increases by 1 year, then the price decreases for 8.975 euros on average.
round(cor(mydata$Price, mydata$Age), 3)
## [1] -0.23
r = -0.23 #Pearson Correlation Coefficient - it tells you how strong the correlation is.
0.0 - 0.1 very week
0.1 - 0.3 weak
0.3 -0. 7 semi strong
0.7 - 0.9 strong
0.9 - 1.0 very strong
There is weak linear relationship between price and age.
Multiple R-squared = 0.05302 #number between 0 and 1 and it tells you how much variability of the dependent variable is explained by the effect of explanatory variable(s)–> higher it is, better is the model
5.302% of variablitiy of price can be explained by the effect of the age of the apartment.
5. Show the scatterplot matrix between Price, Age and Distance. Based on the matrix determine if there is potential problem with multicolinearity.
library(car)
scatterplotMatrix(mydata[ ,c(-4, -5, -6, -7)],
smooth = FALSE)
Based on the graph there is no potential problem with multicolinearity.
#install.packages(Hmisc)
library(Hmisc)
##
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:base':
##
## format.pval, units
rcorr(as.matrix(mydata[ , 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
6. Estimate the multiple regression function: Price = f(Age, Distance). Save it in object named fit2. ####
fit2 <- lm(Price ~ Age + Distance,
data = mydata)
7. Check the multicolinearity with VIF statistics. Explain the findings.
vif(fit2)
## Age Distance
## 1.001845 1.001845
VIF is low with all the variables. It is important that it is below 5.
mean(vif(fit2))
## [1] 1.001845
Mean of VIF statistics is relatively low. It is also okay, because it is below 5.
8. Calculate standardized residuals and Cooks Distances for model fit2. Remove any potentially problematic units (outliers or units with high influence).
mydata$StdResid <- round(rstandard(fit2), 3) #Standardized residuals
mydata$CooksD <- round(cooks.distance(fit2), 3) #Cooks distances
hist(mydata$StdResid,
col = "pink",
xlab = "Standardized residuals",
ylab = "Frequency",
main = "Histogram of standardized residuals")
Absolute values are between -3 and 3, which means we do not have any potential outliers.
shapiro.test(mydata$StdResid)
##
## Shapiro-Wilk normality test
##
## data: mydata$StdResid
## W = 0.95303, p-value = 0.003645
H0: Variable is normally distributed H1: Variable is not normally distributed
p < 5% - We reject the null hypothesis. We assume variable is not normally distributed.
hist(mydata$CooksD,
col = "coral1",
xlab = "Cooks distance",
ylab = "Frequency",
main = "Histogram of Cooks distances")
We should remove the last unit that is above 0.30. To make a short table to visualize which variables make the difference:
head(mydata[order(mydata$StdResid),],3) #Three units with lowest value of stand. residuals
## Age Distance Price Parking Balcony BalconyN ParkingN StdResid
## 53 7 2 1760 0 1 Yes No -2.152
## 13 12 14 1650 0 1 Yes No -1.499
## 72 12 14 1650 0 0 No No -1.499
## CooksD
## 53 0.066
## 13 0.013
## 72 0.013
head(mydata[order(-mydata$CooksD),], 6) #Six units with highest value of Cooks distance
## Age Distance Price Parking Balcony BalconyN ParkingN StdResid
## 38 5 45 2180 1 1 Yes Yes 2.577
## 55 43 37 1740 0 0 No No 1.445
## 33 2 11 2790 1 0 No Yes 2.051
## 53 7 2 1760 0 1 Yes No -2.152
## 22 37 3 2540 1 1 Yes Yes 1.576
## 39 40 2 2400 0 1 Yes No 1.091
## CooksD
## 38 0.320
## 55 0.104
## 33 0.069
## 53 0.066
## 22 0.061
## 39 0.038
Based on the data above it would be best to remove ID 38, regarding Cooks distance.
mydata <- mydata[-38, ]
fit2 <- lm(Price ~ Age + Distance,
data = mydata)
mydata$StdResid <- round(rstandard(fit2), 3)
mydata$CooksD <- round(cooks.distance(fit2), 3)
Double-check what we have done with removing the unit.
hist(mydata$StdResid,
col = "pink",
xlab = "Standardized residuals",
ylab = "Frequency",
main = "Histogram of standardized residuals")
All absolute values of standard residuals are within -3 and 3. There are no outliers to remove.
shapiro.test(mydata$StdResid)
##
## Shapiro-Wilk normality test
##
## data: mydata$StdResid
## W = 0.95649, p-value = 0.006355
H0: variable is normally distributed H1: variable is not normally distributed
p > 0.005 We cannot reject H0. Variable is normally distributed.
hist(mydata$CooksD,
col = "coral1",
xlab = "Cooks distance",
ylab = "Frequency",
main = "Histogram of Cooks distances")
9. Check for potential heteroskedasticity with scatterplot between standarized residuals and standrdized fitted values. Explain the findings.
First we need standardized fitted values and to get them, we use function scale:
mydata$StdFitted <- scale(fit2$fitted.values)
library(car)
scatterplot(y = mydata$StdResid, x = mydata$StdFitted,
ylab = "Standardized residuals",
xlab = "Standardized fitted values",
boxplots = FALSE,
regLine = FALSE,
smooth = FALSE)
option to draw it is also with gg plot
library(ggplot2)
ggplot(mydata, aes(y=StdResid, x=StdFitted)) +
geom_point() +
ylab ("Standardized residuals") +
xlab("Standardized fitted values") +
stat_smooth(method = "lm", formula = y ~ x, se = F) +
theme_bw() #black and white theme
To check if there is any heteroskeditisity we do Breusch- Pagan 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 -value = 0.087 > 5% - we can’t reject H0. Variance is constant, so we have homoskedasticity.
10. Are standardized residuals distributed normally? Show the graph and formally test it. Explain the findings.
hist(mydata$StdResid,
col = "powderblue",
xlab = "Standard residuals",
ylab = "Frequency",
main = "Histogram of Standard residuals")
shapiro.test(mydata$StdResid)
##
## Shapiro-Wilk normality test
##
## data: mydata$StdResid
## W = 0.95649, p-value = 0.006355
H0: Variable is normally distributed H1: Variable is not normally distributed
p > 0.005 We cannot reject H0 at p > 0.005. We assume that variable is distributed normally. We cannot say that standardized residuals are not distributed normally.
11. Estimate the fit2 again without potentially excluded units and show the summary of the model. Explain all coefficients.
summary(fit2)
##
## Call:
## lm(formula = Price ~ Age + Distance, data = mydata)
##
## 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
b0 = 2456.076 (estimate of regression constant - the estimate of the mean of the dependent variable when the values of all explanatory variables are equal to 0. )
AGE H0: Beta1 = 0 H1: Beta1 != 0 b1 = - 6.464 p < 0.05 If an age of the apartment increase by 1 year, price of the apartment is decreased on average by 6.464 euros (p<0.05), assuming that all other explanatory variables, included in the model, are constant.
DISTANCE H0: Beta2 = 0 H1: Beta2 != 0 b2 = - 22.955 p = 2.52 * 10^-12 < 0.001 If a distance of the apartment from the city center is increased by 1km, price od the apartment is decreased on average by 22.955 euros (p<0.001), assuming that all other explanatory variables, included in the model, are constant.
Multiple-R2: 0.4838 48.38 % of variability of price of the apartment can be explained by the effect of explanatory variable(s).
12. Estimate the linear regression function Price = f(Age, Distance, Parking and Balcony). Be careful to correctly include categorical variables. Save the object named fit3
fit3 <- lm(Price ~ Age + Distance + ParkingN + BalconyN,
data = mydata)
summary(fit3)
##
## Call:
## lm(formula = Price ~ Age + Distance + ParkingN + BalconyN, data = mydata)
##
## 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 ***
## ParkingNYes 167.531 62.864 2.665 0.00933 **
## BalconyNYes -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
13. With function anova check if model fit3 fits data better than model fit2.
anova(fit2, fit3)
## Analysis of Variance Table
##
## Model 1: Price ~ Age + Distance
## Model 2: Price ~ Age + Distance + ParkingN + BalconyN
## 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.05 We reject the null hypothesis (H0) at p < 0.05. Model 3 is better, because it explains more variability in Price.
14. Show the results of fit3 and explain regression coefficient for both categorical variables. Can you write down the hypothesis which is being tested with F-statistics, shown at the bottom of the output?
summary(fit3)
##
## Call:
## lm(formula = Price ~ Age + Distance + ParkingN + BalconyN, data = mydata)
##
## 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 ***
## ParkingNYes 167.531 62.864 2.665 0.00933 **
## BalconyNYes -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
PARKING H1: Beta3 = 0 H2: Beta3 != 0 b3 = 167.531 p < 0.05 Assuming that all other variables are the same, the apartment with parking have on average by 167.531 eur higher price compared to apartments without the parking at p < 0.05.
BALCONY H1: Beta4 = 0 H2: Beta4 != 0 p > 0.05
we cannot say that Balcony has statistical effect on Price, because p-value is to high. We do not explain statistically not significant coefficients.
F-STATISTICS H0: RO2 = 0 H1: Ro2 != 0
F = 22.04 p - value = 3.01 * 10^-12 p < 0.001 We reject H0 at p < 0.001. We can say that population coefficent of determination is more than 0, meaning that we found linear relationship between Price of the apartment and explanatory variables included in the model.
15. Save fitted values and calculate the residual for apartment ID2.
mydata$Fitted <- fitted.values(fit3)
mydata$Residuals <- residuals(fit3)
head(mydata[colnames(mydata) %in% c("Apartment", "Price", "Fitted", "Residuals")])
## Price Fitted Residuals
## 1 1640 1705.952 -65.95206
## 2 2800 2372.197 427.80292
## 3 1660 1721.159 -61.15894
## 4 1850 1563.431 286.56890
## 5 1640 2012.244 -372.24396
## 6 1770 1908.177 -138.17733
e= Y- Y(fitted)
Residual for the apartment 2 is:
e = 2800 - 2372.197 = 427.80292