Author: Nik Kovač

Research question 1: 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?

1 Data

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
  • Sample size: 50000 in the beginning but I will lower it to 200
  • Unit of observation: Houses

Explanation of dataset:

  • SquareFeet: Size of the house in square feet
  • Bedrooms: Number of bedrooms in the house
  • Bathrooms: Number of bathrooms in the house
  • Neighborhood: The type of area the house is located in (Rural, Suburb, Urban)
  • Price: The price of the house in dollars

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:

  • From our sample of 200 houses, 74 of them are in a rural area, 67 suburb and 59 urban.
  • The cheapest house in our sample costs 38849 dollars and the most expensive 384404.
  • The average size of houses in our sample is 1954 square feet.
  • Up to 50% of the houses in our sample have 3 bedrooms or less

2 Analysis

Multiple regression model:

  • Price = b0 + b1SquareFeet + b2Bedrooms + b3Bathrooms + b4NeighborhoodF

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:

  • H0: There is homoskedasticity
  • H1: There is heteroskedasticity
  • p = 0.591

We cannot reject null hypothesis (p > 0.05) and conclude that we cannot reject homoskedasticity.

Assumption 2: The expected value of errors equals 0

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.

Assumption 4: Normal distribution of errors

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:

  • H0: Errors are normally distributed
  • H1: Errors are not normally distributed
  • p = 0.311

We cannot reject null hypothesis (p > 0.05) and conclude that we cannot reject normal distribution of errors.

Assumption 5: Errors are independent

This assumption is also met because each unit (house) is only measured once.

Assumption 6: No perfect multicolinearity (or too strong)

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.

Assumption 7: The number of units is larger than the number of estimated parameters

This assumption is also met because our sample size is larger than the number of estimated parameters: n > k

Additional requirements:
  • Numeric or dichotomous variables (met)
  • Variables must vary (met)
  • Not too strong multicolinearity (met and checked up above)

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.

Regression Analysis:

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:

  • Regression model: Price = -12002.64 + 91.34SquareFeet + 6807.19Bedrooms + 6847.61Bathrooms + 17403.76NeighborhoodFSuburb + 19824.75*NeighborhoodFUrban

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:

  • H0: rho^2 = 0
  • H1: rho^2 > 0
  • p < 0.001

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).

3 Conclusion

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?

  • Statistically, we cannot claim that number of bathrooms or number of bedrooms affect the price of a house, but we can claim that that size (p < 0.001) has a positive impact and both sururb (p = 0.047), and urban (p = 0.031) types of neighborhoods compared to rural, also have a positive impact on price.