Author: Nik Kovač
mydata <- read.table("./housing_price_dataset.csv", header=TRUE, sep=",", dec=";") ##Creating data frame by importing a csv file
head(mydata)
## SquareFeet Bedrooms Bathrooms Neighborhood Price
## 1 2126 4 1 Rural 215355.2836
## 2 2459 3 2 Rural 195014.2216
## 3 1860 2 1 Suburb 306891.0121
## 4 2294 2 1 Urban 206786.7872
## 5 2130 5 2 Suburb 272436.2391
## 6 2095 2 3 Suburb 198208.8039
Explanation of dataset:
The dataset is called Housing Price Prediction Data and I took it from a website called Kaggle: https://www.kaggle.com/datasets/muhammadbinimran/housing-price-prediction-data/data.
I want to point out that the dataset was created synthetically for learning purposes, that’s why some data will look weird but the professor approved it.
mydata <- mydata[mydata$Price >= 0,] #Removing units with negative values in the column price, because logically nobody would pay another person to take his house
anyNA(mydata) #Checking for NA values
## [1] FALSE
set.seed(123) #Setting a seed
mydata_sample <- mydata[sample(nrow(mydata), 200),] #Taking a random sample of 200 units from our original dataset
table(mydata_sample$Neighborhood) #Because our categorical variable has 3 categories, we need to check which one has the highest amount of units, so I can use it as the base in my regression analysis
##
## Rural Suburb Urban
## 74 67 59
mydata_sample$ID <- seq_along(mydata_sample$Price) #Assigning an "ID" number to each house
mydata_sample$NeighborhoodF <- factor(mydata_sample$Neighborhood,
levels = c("Rural","Suburb","Urban"),
labels = c("Rural","Suburb","Urban")) #Because "Rural" category had the most units, I put it as the first (base)
mydata_sample$Price <- as.numeric(mydata_sample$Price)
mydata_sample$Price <- round(mydata_sample$Price) #Rounding the price column because it had a lot of decimal places
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
mydata_sample <- mydata_sample %>%
select(ID, Price, everything()) #Putting ID first and Price second
head(mydata_sample[,-5]) #Hiding neighborhood so it's not doubled
## ID Price SquareFeet Bedrooms Neighborhood NeighborhoodF
## 2988 1 280842 2681 3 Urban Urban
## 29943 2 244486 2897 4 Urban Urban
## 29727 3 338222 2694 4 Rural Rural
## 37551 4 278630 2591 5 Suburb Suburb
## 2759 5 196539 1510 3 Suburb Suburb
## 45426 6 266072 2873 2 Suburb Suburb
summary(mydata_sample[,c(-1, -6)]) #descriptive statistics of all relevant columns
## Price SquareFeet Bedrooms Bathrooms NeighborhoodF
## Min. : 38849 Min. :1011 Min. :2.00 Min. :1.000 Rural :74
## 1st Qu.:162806 1st Qu.:1466 1st Qu.:3.00 1st Qu.:1.000 Suburb:67
## Median :213788 Median :1930 Median :3.00 Median :2.000 Urban :59
## Mean :215471 Mean :1954 Mean :3.46 Mean :2.015
## 3rd Qu.:268130 3rd Qu.:2410 3rd Qu.:4.00 3rd Qu.:3.000
## Max. :384404 Max. :2982 Max. :5.00 Max. :3.000
From this table we can gather a lot of information and I will explain some:
Multiple regression model:
These variables were chosen to explain the price of a house because I believe they are highly relevant.
From the size of the house, I expect to see a positive impact on the price.
I also believe that the types of neightborhoods impact the price of the house, whereas I trust that houses in rural areas are going to be the cheapest and the houses in urban areas to be the most expensive, assuming everything else is the same.
I expect both the number of bathrooms and bedrooms to have a positive impact on price.
Before we dive into the regression analysis, we have to check all assumptions and requirements: ##### Assumptions 1 and 3: Linearity in parameters and Homoskedasticity We check both of these assumptions with a graph between standardized residuals and standardized fitted values.
fit <- lm(Price ~ SquareFeet + Bedrooms + Bathrooms + NeighborhoodF,
data = mydata_sample)
mydata_sample$StdFitted <- scale(fit$fitted.values)
mydata_sample$StdResid <- round(rstandard(fit), 3)
library(car)
## Loading required package: carData
##
## Attaching package: 'car'
## The following object is masked from 'package:dplyr':
##
## recode
scatterplot(y = mydata_sample$StdResid, x = mydata_sample$StdFitted,
ylab = "Standardized Residuals",
xlab = "Standardized Fitted Values",
boxplots = FALSE,
regLine = FALSE,
smooth = FALSE)
From the graph we can see linearity and homoskedasticity but we will check the second with the Breusch Pagan Test just in case:
#install.packages("olsrr")
library(olsrr)
##
## Attaching package: 'olsrr'
## The following object is masked from 'package:datasets':
##
## rivers
ols_test_breusch_pagan(fit)
##
## 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 = 0.2889117
## Prob > Chi2 = 0.5909188
Explanation of results:
We cannot reject null hypothesis (p > 0.05) and conclude that we cannot reject homoskedasticity.
This assumption is met when all relevant explanatory variables are used in the regression model (that the model is built on the theory). For the sake of this homework, I will assume that this is met since I took all of the variables given in the data set.
We test this assumption with the Shapiro-wilk normality test or graphically with a histogram of standardized residuals:
hist(mydata_sample$StdResid,
xlab = "Standardized Residuals",
ylab = "Frequency",
main = "Histogram of Standardized Residuals")
Since I cannot say with certainty that they are normally distributed, I will also check with the test:
shapiro.test(mydata_sample$StdResid)
##
## Shapiro-Wilk normality test
##
## data: mydata_sample$StdResid
## W = 0.99169, p-value = 0.311
Explanation of results:
We cannot reject null hypothesis (p > 0.05) and conclude that we cannot reject normal distribution of errors.
This assumption is also met because each unit (house) is only measured once.
I will test the 6th assumption together with the requirement of not too strong colinearity between explanatory variables with vif statistics:
library(car)
vif(fit)
## GVIF Df GVIF^(1/(2*Df))
## SquareFeet 1.009971 1 1.004973
## Bedrooms 1.006315 1 1.003153
## Bathrooms 1.020821 1 1.010357
## NeighborhoodF 1.026583 2 1.006581
Because I have a categorical variable with more than 2 categories, the GVIF^(1/(2*Df)) part of the result has to be below square root of 5, which is approximately 2.25. As we can see from the results all of them are fairly below 2.25 and the average is very close to 1.
This assumption is also met because our sample size is larger than the number of estimated parameters: n > k
Lastly, we make sure that there are no outliers or units with a large impact:
hist(mydata_sample$StdResid,
xlab = "Standardized Residuals",
ylab = "Frequency",
main = "Histogram of Standardized Residuals")
We’ve already seen this histogram when we were checking for normality, but this time check if there are any values above 3 or below -3. There clearly aren’t any so we move on to check units with a large impact:
mydata_sample$CooksD <- round(cooks.distance(fit), 3)
hist(mydata_sample$CooksD,
xlab = "Cook's distance",
ylab = "Frequency",
main = "Histogram of Cook's distances")
Everything seems in order because there aren’t any values above 1 or any gaps in between, but we can additionally check it with tables:
head(mydata_sample[order(mydata_sample$StdResid), c("ID","StdResid")], 3)
## ID StdResid
## 24189 14 -2.717
## 37791 151 -2.243
## 47507 96 -2.240
head(mydata_sample[order(-mydata_sample$StdResid), c("ID","StdResid")], 3)
## ID StdResid
## 13806 146 2.411
## 37566 80 2.296
## 25948 196 1.860
head(mydata_sample[order(-mydata_sample$CooksD), c("ID","CooksD")], 6)
## ID CooksD
## 37566 80 0.034
## 24189 14 0.030
## 48004 56 0.030
## 1836 158 0.029
## 47507 96 0.027
## 13806 146 0.025
For the standardized residuals everything checks out. For Cook’s distances ID 80 might look a little suspicious but I don’t think it’s a problem.
All assumptions and requirements were checked and met. This means we can use the ols method, which in this case also becomes the best linear unbiased estimator (BLUE).
summary(fit)
##
## Call:
## lm(formula = Price ~ SquareFeet + Bedrooms + Bathrooms + NeighborhoodF,
## data = mydata_sample)
##
## Residuals:
## Min 1Q Median 3Q Max
## -138267 -31794 -1313 36886 122591
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -12002.638 19898.111 -0.603 0.5471
## SquareFeet 91.340 6.563 13.918 <2e-16 ***
## Bedrooms 6807.192 3533.829 1.926 0.0555 .
## Bathrooms 6847.610 4478.582 1.529 0.1279
## NeighborhoodFSuburb 17403.755 8702.702 2.000 0.0469 *
## NeighborhoodFUrban 19824.752 9090.449 2.181 0.0304 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 51490 on 194 degrees of freedom
## Multiple R-squared: 0.527, Adjusted R-squared: 0.5148
## F-statistic: 43.23 on 5 and 194 DF, p-value: < 2.2e-16
Explanation of results:
Hypotheses for all partial regression coefficients:
H0: The partial regression coefficient equals 0 (b = 0)
H1: The partial regression coefficient does not equal 0 (b =/= 0)
We do not interpret statistically insignificant regression coefficients, therefore I won’t interpret the variables Bedrooms and Bathrooms.
b1 = 91.34; If the size of a house increases by 1 square foot, the price would on average increase by 91.34 dollars (p < 0.001), assuming everything else remains the same.
b4 = 17403.76; Given the values of all other variables, the houses located in the suburbs are on average 17403.76 dollars more expensive compared to houses in rural areas (p = 0.047).
b5 = 19824.75; Given the values of all other variables, the houses located in urban areas are on average 19824.75 dollars more expensive compared to houses in rural areas (p = 0.031).
Multiple R^2 = 0.527; 52.7% of variability of price can be explained by the linear effect of size, number of bedrooms, number of bathrooms and the type of neighborhood (rural, urban and suburb).
F-statistic:
Based on the sample data, we can reject the null hypothesis (p < 0.001) and conclude that we can explain some variability of price of a house with the explanatory variables (size, number of bedrooms, number of bathrooms and the type of neighborhood).
Research question: How is the price of the house affected by its size, number of bedrooms, number of bathrooms and the type of neighborhood it is located in?