RQ:How area and furnishing status effect the price of houses?
Data set is from Kaggle: https://www.kaggle.com/datasets/harishkumardatalab/housing-price-prediction/data

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 <- read.table("/home/mohor/Desktop/MVA/HW1/Housing.csv", header=TRUE, sep=",", dec=".")
mydata <- mydata[ , c(1, 2, 13)]
mydata <- mutate(mydata, ID = 1:n()) # add unique ID to each row
mydata$area <- round(mydata$area*0.092903) #transformation to metric system m2, so I will have better feeling how price changes
head(mydata)
##      price area furnishingstatus ID
## 1 13300000  689        furnished  1
## 2 12250000  832        furnished  2
## 3 12250000  925   semi-furnished  3
## 4 12215000  697        furnished  4
## 5 11410000  689        furnished  5
## 6 10850000  697   semi-furnished  6

Descriptions:
price - Price of house in $.
area - area in m2.
furnishing status - furnished/semi-furnished/unfurnished

Unit of observation: house
Sample size: 545

table(mydata$furnishingstatus)
## 
##      furnished semi-furnished    unfurnished 
##            140            227            178

To set base for dummy variable. I will set semi-furnished as base, because is the most frequent in this data set.

Factoring:

mydata$furnishingstatusF <- factor(mydata$furnishingstatus,
                         levels = c ("semi-furnished", "unfurnished", "furnished"),
                         labels = c ("semi-furnished", "unfurnished", "furnished"))
head(mydata)
##      price area furnishingstatus ID furnishingstatusF
## 1 13300000  689        furnished  1         furnished
## 2 12250000  832        furnished  2         furnished
## 3 12250000  925   semi-furnished  3    semi-furnished
## 4 12215000  697        furnished  4         furnished
## 5 11410000  689        furnished  5         furnished
## 6 10850000  697   semi-furnished  6    semi-furnished
#checking if there are any missing values in the dataset  
any_na <- any(is.na(mydata)) 
if (any_na) {
  na_values <- which(is.na(mydata), arr.ind = TRUE)
}
# Removing rows with NA values
mydata <- na.omit(mydata)
any_na <- any(is.na(mydata)) 
print(any_na)
## [1] FALSE

Descriptive statistics:

summary(mydata[ , c(-3, -4)])
##      price               area             furnishingstatusF
##  Min.   : 1750000   Min.   : 153.0   semi-furnished:227    
##  1st Qu.: 3430000   1st Qu.: 334.0   unfurnished   :178    
##  Median : 4340000   Median : 427.0   furnished     :140    
##  Mean   : 4766729   Mean   : 478.5                         
##  3rd Qu.: 5740000   3rd Qu.: 591.0                         
##  Max.   :13300000   Max.   :1505.0

Max price of apartment in sample is 13300000$.
50% of houses in the data set have area bigger than 427.0m2.
We have 227 semi-furnished, 178 unfurnished and 140 furnished apartments in the sample.

library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## The following object is masked from 'package:dplyr':
## 
##     recode
#we show only numeric data
scatterplotMatrix(mydata[ ,c(1, 2)],
                  smooth = FALSE) 

We can see that relation between dependable and explanatory variable is linear.
We can also observe that correlation between price and area is positive and quite strong, so we except that area(size in m2) will be good explanatory variable for price.

Since we are talking about prices of houses, I chose in my opinion two most important indicators for setting the price: area(numerical) and furnishing status(categorical). I think those are the best variables, which will allow me to explain variability of price. I expect that on average the bigger will be house(area), the more expensive will be. And similar with the furnishing status of the house. I expect furnished houses will be more expensive than semi-furnished, and that will be more expensive than unfurnished.

fit1 <- lm(price ~ area + furnishingstatusF, #Dependent and explanatory variables
           data = mydata) #Name of the data frame
summary(fit1)
## 
## Call:
## lm(formula = price ~ area + furnishingstatusF, data = mydata)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -4056434  -980757  -227620   645551  7061276 
## 
## Coefficients:
##                              Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                   2687034     188092  14.286  < 2e-16 ***
## area                             4627        330  14.020  < 2e-16 ***
## furnishingstatusFunfurnished  -696367     153685  -4.531 7.23e-06 ***
## furnishingstatusFfurnished     363981     165045   2.205   0.0278 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1529000 on 541 degrees of freedom
## Multiple R-squared:  0.3358, Adjusted R-squared:  0.3321 
## F-statistic: 91.17 on 3 and 541 DF,  p-value: < 2.2e-16

Checking the assupmtions

Multicolinearity

vif(fit1) #Multicolinearity
##                       GVIF Df GVIF^(1/(2*Df))
## area              1.030356  1        1.015064
## furnishingstatusF 1.030356  2        1.007504

We have all variables are under 5(first colomn) or under square root of 5(second colomn) for categorical variable(furnishing status), because it has 3 categories.

mean(vif(fit1))
## [1] 1.180547

As well is mean of VIFs near to 1. So we conclude that we do not have problem with multicolinearity.

Outliears and high impact units

mydata$StdResid <- round(rstandard(fit1), 3) 
mydata$CooksD <- round(cooks.distance(fit1), 3)

hist(mydata$StdResid, 
     xlab = "Standardized residuals", 
     ylab = "Frequency", 
     main = "Histogram of standardized residuals")

Here we check 2 things: outliers and normality of errors.
Outliers: We have a problem because we have some units outside interval (-3, 3). We will have to remove them.
Normality of errors: We have sufficiently large sample(500+), so we can assume it.

head(mydata[order(mydata$StdResid), c("ID", "StdResid")], 6)
##      ID StdResid
## 404 404   -2.698
## 212 212   -2.451
## 126 126   -2.312
## 453 453   -2.239
## 355 355   -1.893
## 187 187   -1.880

To remove IDs: None

head(mydata[order(-mydata$StdResid), c("ID", "StdResid")], 10)
##    ID StdResid
## 1   1    4.639
## 4   4    3.902
## 2   2    3.520
## 10 10    3.503
## 3   3    3.480
## 5   5    3.397
## 6   6    3.241
## 14 14    3.079
## 12 12    2.896
## 17 17    2.805

To remove IDs: 1, 4, 2, 10, 3, 5, 6, 14

hist(mydata$CooksD, 
     xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histrogram of Cooks distances")

As we can see from graph above, we have a gap. We will have to remove some values.

head(mydata[order(-mydata$CooksD), c("ID", "CooksD")], 10)
##      ID CooksD
## 126 126  0.068
## 404 404  0.062
## 1     1  0.045
## 212 212  0.043
## 3     3  0.042
## 2     2  0.036
## 4     4  0.033
## 5     5  0.024
## 14   14  0.022
## 10   10  0.019

We find some HIU(high influence units) IDs: 126, 404, 1, 212, 3, 2, 4

library(dplyr)
#remove HIU and outliers
mydata <- mydata %>%
  filter(!ID %in% c(126, 404, 1, 212, 3, 2, 4, 10, 5, 6, 14)) 

Let’s check if we removed everything as expected.

hist(mydata$StdResid, 
     xlab = "Standardized residuals", 
     ylab = "Frequency", 
     main = "Histogram of standardized residuals")

hist(mydata$CooksD, 
     xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histrogram of Cooks distances")

So from the graphs above we can see that we successfully removed all outliers and HIU. I know that there is still a gap but, I will assume it OK, stop removing outliers and continue with the analysis.

Normality of standardized residuals

shapiro.test(mydata$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata$StdResid
## W = 0.9671, p-value = 1.433e-09

H0: Residuals are normally distributed.
H1: Residuals are not normally distributed.
We can reject H0(p<0.001) and conclude that residuals are not normally distributed.
But as we said, due to having a large enough sample, normality of error is not really relevant.

Homoscedasticity

fit2 <- lm(price ~ area + furnishingstatusF, #Dependent and explanatory variables
           data = mydata) #Name of the data frame

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)

On the scatter plot above we checked 2 things: linearity and homoscedasticity.
From the scatter plot we can see that homoscedasticity is violated. But we will check it for sure with Breush Pagan test.
Linearity is OK.

library(olsrr)
## 
## Attaching package: 'olsrr'
## The following object is masked from 'package:datasets':
## 
##     rivers
ols_test_breusch_pagan(fit1)
## 
##  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          =    106.5220 
##  Prob > Chi2   =    5.666105e-25

Ho: the variance is constant.
H1: the variance is not constant.
We can reject H0(p<0.001) and conclude that variance is not constant(We have heteroscedasticity). We will have to use robust standard errors.

Assumptions and requirments summary
Assumpptions:
- Linearity(dependent variable is linear function of the parameters) is met.
- The expected value of the errors equals 0. In the reality a lot more things affect price of houses(so I should include more explanatory variables), but due to academic reasons I will say that my model include all relevant explanatory variables and assume that this assumption is met.
- Homoskedasticity assumption isn’t met in my model. That’s why I will use robust standard errors.
- Normal distribution of errors. This assumption is met because I use sufficiently large sample(n=545).
- Errors are independent. Each unit is observed only once, so this assumption is also met.
- No perfect multiloniearity. I checked that and this assumption is met.
- n>k, is met. Sample size is much bigger then number of parameters I want to estimate.

Requirements:
- Dependent variable is numeric, explanatory variables are numeric and categorical(dummy). This requirement is met.
- Each explanatory variable must vary. Is met, because areas are different as well furnishing status differ among houses.
- Outliers and HIU have been removed.
- There is no too strong multicolinearity. I checked it with VIF statistics and requirement is met.

Now we can fit a model again.

library(estimatr)
fit3 <- lm_robust(price ~ area + furnishingstatusF, #Dependent and explanatory variables
           se_type = "HC1",
           data = mydata)
summary(fit3)
## 
## Call:
## lm_robust(formula = price ~ area + furnishingstatusF, data = mydata, 
##     se_type = "HC1")
## 
## Standard error type:  HC1 
## 
## Coefficients:
##                              Estimate Std. Error t value  Pr(>|t|) CI Lower
## (Intercept)                   2630460   161137.6  16.324 7.890e-49  2313913
## area                             4682      348.5  13.436 1.259e-35     3998
## furnishingstatusFunfurnished  -671169   134980.3  -4.972 8.948e-07  -936331
## furnishingstatusFfurnished     208704   153650.1   1.358 1.749e-01   -93134
##                              CI Upper  DF
## (Intercept)                   2947007 530
## area                             5367 530
## furnishingstatusFunfurnished  -406007 530
## furnishingstatusFfurnished     510542 530
## 
## Multiple R-squared:  0.3625 ,    Adjusted R-squared:  0.3589 
## F-statistic: 89.15 on 3 and 530 DF,  p-value: < 2.2e-16

Conclusion:
If square area increases by 1m2, price will on average increase by 4682 $ (p<0.001), assuming everything else stays the same.
Given the area of house, if house is unfurnished is on average 671169 $ cheaper compared to semi-furnished(p<0.001).
Given the area of house, if house is furnished is on average 208704 $ more expensive compared to semi-furnished(p<0.001).
R2: 36,25% of variability of price is explained by variability of area and furnishing status.

F-statistics
H0: beta1 = beta2 = 0
H1: At least one is different than 0.
We reject H0 at p<0.001 and conclude that at least one of the variables (area, furnishing status) has at least some impact on the price of house.

So now we can answer our research question and conclude that on average the bigger will be area of the house, the higher will be price of the house. Similar is with furnishing status of house, on average we can say that the more furnished is house the higher will be the price.

Model comparison:
In the real world price of houses depends on a lot of factors. As I mentioned before we didn’t include all important explanatory variables, but due to academic reasons we assume that we included all and 2nd assumption is met. Now I will create new(simpler) model to show comparison between two different models.

fit4 <- lm_robust(price ~ area, 
           se_type = "HC1",
           data = mydata)
summary(fit4)
## 
## Call:
## lm_robust(formula = price ~ area, data = mydata, se_type = "HC1")
## 
## Standard error type:  HC1 
## 
## Coefficients:
##             Estimate Std. Error t value  Pr(>|t|) CI Lower CI Upper  DF
## (Intercept)  2319427     146337   15.85 1.270e-46  2031957  2606897 532
## area            4984        339   14.70 2.607e-41     4318     5650 532
## 
## Multiple R-squared:  0.318 , Adjusted R-squared:  0.3167 
## F-statistic: 216.2 on 1 and 532 DF,  p-value: < 2.2e-16

I created this model just to compare it with my model above(fit 3).
R2: 31,8% of variability of price is explained by variability of area(explanatory variable).

We can see from R2 that first model(fit3) explains more variability of price(36,3% > 31,8%). But to prove that is worth using more complex model(that difference between models is statistically significant) I will show it with the test.

library(lmtest)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
waldtest(fit4, fit3, test = "F")
## Wald test
## 
## Model 1: price ~ area
## Model 2: price ~ area + furnishingstatusF
##   Res.Df Df      F   Pr(>F)    
## 1    532                       
## 2    530  2 18.213 2.24e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

H0: First model is better.
H1: The second model is better.
We can reject H0 at (p<0,001) and conclude that model 2 (area and furnishing status) is better than model 1 (only area). So we can conclude that furnishing status explains some additional variability of price.