mydata <- read.table("./insurance.csv", header=TRUE, sep=",", dec=".")
head(mydata) #show first 6 rows of dataframe
##   age    sex    bmi children smoker    region   charges
## 1  19 female 27.900        0    yes southwest 16884.924
## 2  18   male 33.770        1     no southeast  1725.552
## 3  28   male 33.000        3     no southeast  4449.462
## 4  33   male 22.705        0     no northwest 21984.471
## 5  32   male 28.880        0     no northwest  3866.855
## 6  31 female 25.740        0     no southeast  3756.622

Description: -Age: The insured person’s age. -Sex: Gender (male or female) of the insured. -BMI (Body Mass Index): A measure of body fat based on height and weight. -Children: The number of dependents covered. -Smoker: Whether the insured is a smoker (yes or no). -Region: The geographic area of coverage. -Charges: The medical insurance costs incurred by the insured person.

Data: Healthcare Insurance Author: Arun Jangir and willian oliveira source: https://www.kaggle.com/datasets/willianoliveiragibin/healthcare-insurance

Research Question 1: I am interested in whether there is a difference in Body Mass Index (bmi) between insured non-smokers and insured smokers.

unit: insured person variables: bmi, smoker (yes/no)

#install.packages("psych")
library(psych)
## Warning: Paket 'psych' wurde unter R Version 4.3.2 erstellt
## 
## Attache Paket: 'psych'
## Die folgenden Objekte sind maskiert von 'package:ggplot2':
## 
##     %+%, alpha
## Das folgende Objekt ist maskiert 'package:car':
## 
##     logit
describeBy(mydata$bmi, mydata$smoker)
## 
##  Descriptive statistics by group 
## group: no
##    vars    n  mean   sd median trimmed mad   min   max range skew kurtosis   se
## X1    1 1064 30.65 6.04  30.35   30.49   6 15.96 53.13 37.17 0.28    -0.07 0.19
## ------------------------------------------------------------------------------------------ 
## group: yes
##    vars   n  mean   sd median trimmed  mad  min   max range skew kurtosis   se
## X1    1 274 30.71 6.32  30.45   30.53 6.78 17.2 52.58 35.38 0.31    -0.07 0.38

Description of groups - group no smoker: n=1064, average bmi is 30,65: Half of the insured non-smokers have a bmi score of 30,65 or less - group smoker: n=274, average bmi is 30,71; Half of the insured smokers have a bmi score of 30,71 or less

library(ggpubr)
ggqqplot(mydata,
         "bmi",
         facet.by = "smoker")

Independent Samples assumptions for parametric: -two different groups of units: smoker and non-smoker -variable bmi is numeric -distribution of variable is normal in both populations (Shapiro-wilk-test) -variable has the same variance in both populations (Welch-correction) –> Assuming that assumptions are met –> parametric

Independent t-test - parametric test H0: population arithmetic means are the same H1: population arithmetic means are not the same

t.test(mydata$bmi ~ mydata$smoker, 
       paired = FALSE,
       var.equal = FALSE,
       alternative = "two.sided")
## 
##  Welch Two Sample t-test
## 
## data:  mydata$bmi by mydata$smoker
## t = -0.13352, df = 410.9, p-value = 0.8938
## alternative hypothesis: true difference in means between group no and group yes is not equal to 0
## 95 percent confidence interval:
##  -0.8907341  0.7774265
## sample estimates:
##  mean in group no mean in group yes 
##          30.65180          30.70845

Result: p-value=0.894, that means we can not reject H0–> population arithmetic means are the same in both groups of smoking

library(effectsize)
## 
## Attache Paket: 'effectsize'
## Das folgende Objekt ist maskiert 'package:psych':
## 
##     phi
## Das folgende Objekt ist maskiert 'package:robustHD':
## 
##     standardize
effectsize::cohens_d(mydata$bmi ~ mydata$smoker,
                     pooled_sd = FALSE)
## Cohen's d |        95% CI
## -------------------------
## -9.16e-03 | [-0.14, 0.13]
## 
## - Estimated using un-pooled SD.
interpret_cohens_d(-9.16e-03, rules = "sawilowsky2009")
## [1] "tiny"
## (Rules: sawilowsky2009)

The effectsize is tiny.

CHheck for assumption normality with Shapiro-Wilk-Test H0: variable is normal distributed H1: variable is not normal distributed

library(rstatix)
## Warning: Paket 'rstatix' wurde unter R Version 4.3.2 erstellt
## 
## Attache Paket: 'rstatix'
## Die folgenden Objekte sind maskiert von 'package:effectsize':
## 
##     cohens_d, eta_squared
## Das folgende Objekt ist maskiert 'package:stats':
## 
##     filter
mydata %>%
  group_by(smoker) %>%
  shapiro_test(bmi)
## # A tibble: 2 × 4
##   smoker variable statistic        p
##   <chr>  <chr>        <dbl>    <dbl>
## 1 no     bmi          0.994 0.000422
## 2 yes    bmi          0.991 0.0852

Result: group no-smoker p-value<0,001 that means we have to reject H0 and is not normally distributed –> we have to use non-parametic test

Independent non-parametric test –> Wilcoxon Rank Sum Test H0: location distribution is the same H1: location distribution is not the same

wilcox.test(mydata$bmi ~ mydata$smoker,
            paired = FALSE,
            correct = FALSE,
            exact = FALSE,
            alternative = "two.sided")
## 
##  Wilcoxon rank sum test
## 
## data:  mydata$bmi by mydata$smoker
## W = 145309, p-value = 0.9358
## alternative hypothesis: true location shift is not equal to 0

Result: p-value = 0.936 –> we can not reject H0 –> location distribution in both groups is the same

library(effectsize)
effectsize(wilcox.test(mydata$bmi ~ mydata$smoker,
                       paired = FALSE,
                       correct = FALSE,
                       exact = FALSE,
                       alternative = "two.sided"))
## r (rank biserial) |        95% CI
## ---------------------------------
## -3.15e-03         | [-0.08, 0.07]
interpret_rank_biserial(-3.15e-03)
## [1] "tiny"
## (Rules: funder2019)

Conclusion: The non-parametric Wilcoxon Rank Sum Test is more appropriate since the Shaprio-Wilk Test showed that the distribution of the variable is not normal in both populations and therefore the assumptions for parametric testing are not met. We can not reject H0, meaning that the location distribution of bmi in the group of smokers and the group of non-smokers is not different from each other.

Research Question 2 - Regression

mydata2 <- read.table("./Housing.csv", header=TRUE, sep=",", dec=".")

head(mydata2)
##      price area bedrooms bathrooms stories mainroad guestroom basement hotwaterheating airconditioning parking prefarea
## 1 13300000 7420        4         2       3      yes        no       no              no             yes       2      yes
## 2 12250000 8960        4         4       4      yes        no       no              no             yes       3       no
## 3 12250000 9960        3         2       2      yes        no      yes              no              no       2      yes
## 4 12215000 7500        4         2       2      yes        no      yes              no             yes       3      yes
## 5 11410000 7420        4         1       2      yes       yes      yes              no             yes       2       no
## 6 10850000 7500        3         3       1      yes        no      yes              no             yes       2      yes
##   furnishingstatus
## 1        furnished
## 2        furnished
## 3   semi-furnished
## 4        furnished
## 5        furnished
## 6   semi-furnished

Description -price: price of the Houses in US-Dollar -area: size of the house in square meters -bedrooms: amount of bedrooms -bathrooms: amount of bathrooms -stories: amount of stories -mainroad: connected to Main Road (yes/no), Dummy -guestroom: house has a guestroomyes or no, Dummy -basement: house has basement yes or no, Dummy -hotwaterheating: house has hotwaterheating yes or no, Dummy -airconditioning: house has airconditioning yes or no, Dummy -parking: number of house parkings -prefarea: located in an area that is preferred yes or no, Dummy -furnishingstatus: house is furnished, semi-furnished, unfurnished, 2x Dummy

Data: Housing Prices Dataset Author: M YASSER H Source: https://www.kaggle.com/datasets/yasserh/housing-prices-dataset

summary(mydata2)
##      price               area          bedrooms       bathrooms        stories        mainroad        
##  Min.   : 1750000   Min.   : 1650   Min.   :1.000   Min.   :1.000   Min.   :1.000   Length:545        
##  1st Qu.: 3430000   1st Qu.: 3600   1st Qu.:2.000   1st Qu.:1.000   1st Qu.:1.000   Class :character  
##  Median : 4340000   Median : 4600   Median :3.000   Median :1.000   Median :2.000   Mode  :character  
##  Mean   : 4766729   Mean   : 5151   Mean   :2.965   Mean   :1.286   Mean   :1.806                     
##  3rd Qu.: 5740000   3rd Qu.: 6360   3rd Qu.:3.000   3rd Qu.:2.000   3rd Qu.:2.000                     
##  Max.   :13300000   Max.   :16200   Max.   :6.000   Max.   :4.000   Max.   :4.000                     
##   guestroom           basement         hotwaterheating    airconditioning       parking         prefarea        
##  Length:545         Length:545         Length:545         Length:545         Min.   :0.0000   Length:545        
##  Class :character   Class :character   Class :character   Class :character   1st Qu.:0.0000   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character   Median :0.0000   Mode  :character  
##                                                                              Mean   :0.6936                     
##                                                                              3rd Qu.:1.0000                     
##                                                                              Max.   :3.0000                     
##  furnishingstatus  
##  Length:545        
##  Class :character  
##  Mode  :character  
##                    
##                    
## 

Research Question 2: Potential house buyers want to know the effect of the size (area) of an house on the price of the house.They are also interested, if other variables such as amount of bathrooms and bedrooms or stories have an effect on the prize.

library(pastecs)
round(stat.desc(mydata2[]), 2)
##                     price       area bedrooms bathrooms stories mainroad guestroom basement hotwaterheating
## nbr.val      5.450000e+02     545.00   545.00    545.00  545.00       NA        NA       NA              NA
## nbr.null     0.000000e+00       0.00     0.00      0.00    0.00       NA        NA       NA              NA
## nbr.na       0.000000e+00       0.00     0.00      0.00    0.00       NA        NA       NA              NA
## min          1.750000e+06    1650.00     1.00      1.00    1.00       NA        NA       NA              NA
## max          1.330000e+07   16200.00     6.00      4.00    4.00       NA        NA       NA              NA
## range        1.155000e+07   14550.00     5.00      3.00    3.00       NA        NA       NA              NA
## sum          2.597867e+09 2807045.00  1616.00    701.00  984.00       NA        NA       NA              NA
## median       4.340000e+06    4600.00     3.00      1.00    2.00       NA        NA       NA              NA
## mean         4.766729e+06    5150.54     2.97      1.29    1.81       NA        NA       NA              NA
## SE.mean      8.012083e+04      92.96     0.03      0.02    0.04       NA        NA       NA              NA
## CI.mean.0.95 1.573841e+05     182.60     0.06      0.04    0.07       NA        NA       NA              NA
## var          3.498544e+12 4709512.06     0.54      0.25    0.75       NA        NA       NA              NA
## std.dev      1.870440e+06    2170.14     0.74      0.50    0.87       NA        NA       NA              NA
## coef.var     3.900000e-01       0.42     0.25      0.39    0.48       NA        NA       NA              NA
##              airconditioning parking prefarea furnishingstatus
## nbr.val                   NA  545.00       NA               NA
## nbr.null                  NA  299.00       NA               NA
## nbr.na                    NA    0.00       NA               NA
## min                       NA    0.00       NA               NA
## max                       NA    3.00       NA               NA
## range                     NA    3.00       NA               NA
## sum                       NA  378.00       NA               NA
## median                    NA    0.00       NA               NA
## mean                      NA    0.69       NA               NA
## SE.mean                   NA    0.04       NA               NA
## CI.mean.0.95              NA    0.07       NA               NA
## var                       NA    0.74       NA               NA
## std.dev                   NA    0.86       NA               NA
## coef.var                  NA    1.24       NA               NA
library(car)
scatterplot(mydata2$price ~ mydata2$area,  
            smooth = FALSE,
            boxplots = FALSE,
            ylab = "price in US-Dollar",
            xlab = "area in square meters") 

library(dplyr)
## 
## Attache Paket: 'dplyr'
## Die folgenden Objekte sind maskiert von 'package:pastecs':
## 
##     first, last
## Das folgende Objekt ist maskiert 'package:car':
## 
##     recode
## Die folgenden Objekte sind maskiert von 'package:stats':
## 
##     filter, lag
## Die folgenden Objekte sind maskiert von 'package:base':
## 
##     intersect, setdiff, setequal, union
# Adding ID to dataframe
mydata2 <- mydata2 %>%
  mutate(ID = 1:n())
head(mydata2)
##      price area bedrooms bathrooms stories mainroad guestroom basement hotwaterheating airconditioning parking prefarea
## 1 13300000 7420        4         2       3      yes        no       no              no             yes       2      yes
## 2 12250000 8960        4         4       4      yes        no       no              no             yes       3       no
## 3 12250000 9960        3         2       2      yes        no      yes              no              no       2      yes
## 4 12215000 7500        4         2       2      yes        no      yes              no             yes       3      yes
## 5 11410000 7420        4         1       2      yes       yes      yes              no             yes       2       no
## 6 10850000 7500        3         3       1      yes        no      yes              no             yes       2      yes
##   furnishingstatus ID
## 1        furnished  1
## 2        furnished  2
## 3   semi-furnished  3
## 4        furnished  4
## 5        furnished  5
## 6   semi-furnished  6
fit1 <- lm(price ~ area + bedrooms + bathrooms + stories, 
           data = mydata2) 

mydata2$StdResid <- round(rstandard(fit1), 3) #Standardized residuals for outliers
mydata2$CooksD <- round(cooks.distance(fit1), 3) #Cooks distances for high impact


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

shapiro.test(mydata2$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata2$StdResid
## W = 0.95465, p-value = 6.751e-12
hist(mydata2$CooksD, 
     xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histogram of Cooks distances")

vif(fit1) #Multicolinearity
##      area  bedrooms bathrooms   stories 
##  1.047046  1.311029  1.240516  1.252991
mean(vif(fit1))
## [1] 1.212896

Not too strong multicolinearity.

head(mydata2[order(mydata2$StdResid), c("ID", "StdResid")], 10) #units with lowest value of Cooks distance
##      ID StdResid
## 500 500   -2.933
## 404 404   -2.749
## 230 230   -2.328
## 453 453   -2.235
## 402 402   -2.112
## 524 524   -2.087
## 248 248   -1.961
## 176 176   -1.928
## 489 489   -1.909
## 143 143   -1.864
head(mydata2[order(-mydata2$StdResid), c("ID", "StdResid")], 10) #Ten units with highest value of stand.
##    ID StdResid
## 1   1    4.691
## 5   5    4.569
## 4   4    4.232
## 3   3    3.690
## 21 21    3.548
## 16 16    3.175
## 9   9    3.158
## 14 14    3.092
## 6   6    2.826
## 23 23    2.779
head(mydata2[order(-mydata2$CooksD), c("ID", "CooksD")], 10) #units with highest value of Cooks distance
##      ID CooksD
## 6     6  0.055
## 500 500  0.053
## 404 404  0.047
## 5     5  0.042
## 1     1  0.040
## 3     3  0.038
## 4     4  0.032
## 126 126  0.028
## 9     9  0.023
## 90   90  0.021

Remove units with StdResid above 3 Remove units with CooksD above 0.023 (gaps)

library(dplyr)
mydataC <- mydata2 %>%
  filter(!(ID %in% c(1, 3, 4, 5, 6, 9, 14, 16, 21, 126, 404, 500))) #removing outliers and units with high impact
fit1 <- lm(price ~ area + bedrooms + bathrooms + stories, 
          data = mydataC)

mydataC$StdFitted <- scale(fit1$fitted.values)

library(car)
scatterplot(StdResid ~ StdFitted, 
            ylab = "Standardized residuals", 
            xlab = "Standardized fitted values", 
            smooth = FALSE,
            regLine = FALSE,
            boxplots = FALSE,
            data = mydataC)

library(olsrr)
## Warning: Paket 'olsrr' wurde unter R Version 4.3.2 erstellt
## 
## Attache Paket: 'olsrr'
## Das folgende Objekt ist maskiert '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          =    40.61374 
##  Prob > Chi2   =    1.854977e-10

We can reject H0, there is no homoskedasticity, but heteroskedasticity. That’s why we need to use lm_robust

Model with correction

library(estimatr)
## Warning: Paket 'estimatr' wurde unter R Version 4.3.2 erstellt
fit1 <- lm_robust(price ~ area + bedrooms + bathrooms + stories, 
                  se_type = "HC1",
                  data = mydataC)



summary(fit1)
## 
## Call:
## lm_robust(formula = price ~ area + bedrooms + bathrooms + stories, 
##     data = mydataC, se_type = "HC1")
## 
## Standard error type:  HC1 
## 
## Coefficients:
##              Estimate Std. Error  t value  Pr(>|t|)  CI Lower  CI Upper  DF
## (Intercept)   12471.9  214948.68  0.05802 9.538e-01 -409787.7  434731.5 528
## area            371.1      27.36 13.56219 3.659e-36     317.3     424.9 528
## bedrooms      98783.1   75664.93  1.30553 1.923e-01  -49858.2  247424.4 528
## bathrooms   1179835.0  131832.88  8.94947 6.062e-18  920853.6 1438816.3 528
## stories      536715.4   60845.88  8.82090 1.658e-17  417185.7  656245.1 528
## 
## Multiple R-squared:  0.5812 ,    Adjusted R-squared:  0.5781 
## F-statistic: 169.2 on 4 and 528 DF,  p-value: < 2.2e-16
sqrt(summary(fit1)$r.squared)
## [1] 0.7623813
fit2 <- lm_robust(price ~ area + bedrooms + bathrooms + stories + parking + mainroad + guestroom + basement + hotwaterheating + airconditioning + prefarea + furnishingstatus,  
                  se_type = "HC1",
                  data = mydataC)
summary(fit2)
## 
## Call:
## lm_robust(formula = price ~ area + bedrooms + bathrooms + stories + 
##     parking + mainroad + guestroom + basement + hotwaterheating + 
##     airconditioning + prefarea + furnishingstatus, data = mydataC, 
##     se_type = "HC1")
## 
## Standard error type:  HC1 
## 
## Coefficients:
##                                 Estimate Std. Error t value  Pr(>|t|)  CI Lower  CI Upper  DF
## (Intercept)                     203649.9  229157.36  0.8887 3.746e-01 -246540.1  653839.9 519
## area                               254.2      26.21  9.6992 1.489e-20     202.7     305.7 519
## bedrooms                         57356.8   63199.98  0.9075 3.645e-01  -66802.4  181516.0 519
## bathrooms                      1011131.2  117013.72  8.6411 6.916e-17  781252.4 1241009.9 519
## stories                         439941.1   58596.36  7.5080 2.636e-13  324825.9  555056.4 519
## parking                         160924.6   54038.98  2.9779 3.038e-03   54762.6  267086.6 519
## mainroadyes                     392885.9  100483.85  3.9099 1.046e-04  195480.9  590291.0 519
## guestroomyes                    407985.3  131463.14  3.1034 2.017e-03  149719.9  666250.6 519
## basementyes                     221031.7  104574.18  2.1136 3.502e-02   15591.0  426472.4 519
## hotwaterheatingyes              628490.9  253159.05  2.4826 1.336e-02  131148.4 1125833.3 519
## airconditioningyes              832348.0  101672.30  8.1866 2.096e-15  632608.2 1032087.9 519
## prefareayes                     564843.6  109913.99  5.1390 3.918e-07  348912.6  780774.6 519
## furnishingstatussemi-furnished   21970.0  105583.88  0.2081 8.352e-01 -185454.3  229394.3 519
## furnishingstatusunfurnished    -310527.7  113863.89 -2.7272 6.604e-03 -534218.5  -86836.9 519
## 
## Multiple R-squared:  0.7099 ,    Adjusted R-squared:  0.7027 
## F-statistic: 89.71 on 13 and 519 DF,  p-value: < 2.2e-16

Comparison of models

library(lmtest)
## Warning: Paket 'lmtest' wurde unter R Version 4.3.2 erstellt
## Lade nötiges Paket: zoo
## Warning: Paket 'zoo' wurde unter R Version 4.3.2 erstellt
## 
## Attache Paket: 'zoo'
## Die folgenden Objekte sind maskiert von 'package:base':
## 
##     as.Date, as.Date.numeric
waldtest(fit1, fit2, test = "F")
## Wald test
## 
## Model 1: price ~ area + bedrooms + bathrooms + stories
## Model 2: price ~ area + bedrooms + bathrooms + stories + parking + mainroad + 
##     guestroom + basement + hotwaterheating + airconditioning + 
##     prefarea + furnishingstatus
##   Res.Df Df      F    Pr(>F)    
## 1    528                        
## 2    519  9 26.998 < 2.2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The complex model (model 2) fits the data better.