Multivariate Analysis - Homework 3 - Regression

Patricija Varsek

Source: Data retrived on 21.1.2024, from: https://www.kaggle.com/datasets/willianoliveiragibin/healthcare-insurance

Research question: How do age, body mass index (bmi) and smoking status influence the cost of medical insurance premiums charged to an individual by an insurance company?

library(readxl)
mydata <- read_excel("~/6_IMB/7_Class/7_MultivariateAnalysis/R_HW/Healthcare.xlsx")
mydata <- as.data.frame(mydata)
head(mydata)
##      charges age    sex    bmi children smoker    region
## 1  94329.253  46 female 48.070        2     no northeast
## 2 223315.668  40 female 45.654        1    yes northeast
## 3  21964.732  18 female 45.529        0     no northeast
## 4  73250.482  43 female 45.529        0     no northeast
## 5   7985.815  39 female 45.526        3     no northeast
## 6  12323.936  59   male 45.497        0     no northeast

Data manipulation

set.seed(1) #Setting initial point of sampling.
mydata2 <- mydata[sample(nrow(mydata), 500), ] #Random sample of 500 units.
any_missing <- any(is.na(mydata2)) #checking if there is any missing data
library(tidyr)
mydata3 <- drop_na(mydata2) #Because we got TRUE (there is missing data), I dropped it here
any_missing <- any(is.na(mydata3)) #myData3 is now clear of missing data
#Changing into factor
mydata3$GenderF <- factor(mydata3$sex, 
                          levels = c ("male", "female"), 
                          labels = c ("Male", "Female"))

mydata3$SmokerF <- factor(mydata3$smoker,
                                  levels = c("yes", "no"), 
                                  labels = c("yes", "no"))
head(mydata3)
##       charges age    sex    bmi children smoker    region GenderF
## 1    5325.651  30 female 45.565        3     no southwest  Female
## 2   67701.925  41 female 45.440        1     no southeast  Female
## 3  735817.565  41 female 31.635        1     no northeast  Female
## 4   76403.092  42 female 29.480        2     no southeast  Female
## 5   72567.231  41   male 30.590        2     no northwest    Male
## 6 1374787.235  18   male 21.565        0    yes northeast    Male
##   SmokerF
## 1      no
## 2      no
## 3      no
## 4      no
## 5      no
## 6     yes

Creating clear data set (mydata4) that we will use further on.

#Excluding non necessary data from my sample
mydata4 <- mydata3[,c(-3, -5, -6,-7)]
mydata4$ID <- seq(1,499) #creating ID
mydata4 <- mydata4[c("ID", setdiff(names(mydata4), "ID"))] #moving it to the first row
head(mydata4)
##   ID     charges age    bmi GenderF SmokerF
## 1  1    5325.651  30 45.565  Female      no
## 2  2   67701.925  41 45.440  Female      no
## 3  3  735817.565  41 31.635  Female      no
## 4  4   76403.092  42 29.480  Female      no
## 5  5   72567.231  41 30.590    Male      no
## 6  6 1374787.235  18 21.565    Male     yes

Explain your data

This dataset contains information about person’s age, BMI ad smoking habits and their impact on medical insurance charges.

unit of observation: person sample size: 499

Age: The insured person’s age.

BMI (Body Mass Index): A measure of body fat based on height and weight.

Smoker: Whether the insured is a smoker (yes or no).

Charges: The medical insurance costs incurred by the insured person in dollars.

Descriptive statistics

library(pastecs)
## 
## Attaching package: 'pastecs'
## The following object is masked from 'package:tidyr':
## 
##     extract
summary(mydata4[,c(-1,-5,-6)]) #opis podatkov (brez categoričnih spremenljivk)
##     charges             age             bmi       
##  Min.   :   1137   Min.   :18.00   Min.   :15.96  
##  1st Qu.:  17040   1st Qu.:26.00   1st Qu.:28.79  
##  Median :  95839   Median :38.00   Median :33.11  
##  Mean   : 548108   Mean   :38.95   Mean   :33.90  
##  3rd Qu.: 454930   3rd Qu.:52.00   3rd Qu.:39.23  
##  Max.   :6259287   Max.   :64.00   Max.   :53.13
  • Charges (min = 1137): Minimum Charge chared for medicale insurance is 1137.
  • Age (median = 38.00): 50% of the people are 38.00 years old or less and the other 50% are older than 38.00 years.
  • Bmi (mean= 33.90): Bmi of a person is on average 33.9.

Research question

How do age, body mass index (bmi) and smoking status influence the cost of medical insurance premiums charged to an individual by an insurance company?

Define the multiple regression model with at least briefly justifying the choice of explanatory variables

I expect that age will positively affect the value of healthcare insurance. The older the person is, more likely it is that it will get sick, that’s why the insurance should be higher. Additional, I expect that bmi will also positively affect our dependent variable. If someone has bmi higher than normal, their body is less healthy, there is more chances that it will get sick and insurance should be higher. Furthermore, if someone is smoking, this also negatively impacts a person’s health, which would positively affect the value of the insurance.

Check assumptions

  1. Scatterplot matrix without categorical variables
library(car)
## Loading required package: carData
scatterplotMatrix(mydata4[,c(2,3,4)], 
                  smooth= FALSE)      

Here we check assumptions of multicolinearity and linearity.

  • Linearity is violated - There is no linear relationship between our y and x1, x2, respectively. Therefore, will use log-log model with variables charges and Age.
  • multicolinearity (checked later)

1.2. Correlation matrix

library(Hmisc)
## 
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:base':
## 
##     format.pval, units
rcorr(as.matrix(mydata4[,c(2,3,4)])) #Correlation matrix
##         charges  age   bmi
## charges    1.00 0.17 -0.09
## age        0.17 1.00  0.05
## bmi       -0.09 0.05  1.00
## 
## n= 499 
## 
## 
## P
##         charges age    bmi   
## charges         0.0001 0.0574
## age     0.0001         0.3121
## bmi     0.0574  0.3121

We can check if the effect is statistically significant.

Charges and Age:

H0: Rho(charges,age) = 0
H1: Rho(charges,age) =/= 0
We can reject H0 (p<0.001). Age affects charges of healthcare insurance. 

Charges and bmi:

H0: Rho(charges,bmi) = 0
H1: Rho(charges,bmi) =/= 0
We can not reject H0. Bmi doesn't affect charges of healthcare insurance.

1.3. Due to violation of linearity we will turn variables Charge and Age in to logaritmic variables.

mydata4$lnCharges <- log(mydata4$charges)
mydata4$lnAge <- log(mydata4$age)

New variables:

head(mydata4[colnames(mydata4) %in% c("lnCharges", "lnAge", "bmi", "SmokerF")] )
##      bmi SmokerF lnCharges    lnAge
## 1 45.565      no   8.58029 3.401197
## 2 45.440      no  11.12287 3.713572
## 3 31.635      no  13.50874 3.713572
## 4 29.480      no  11.24378 3.737670
## 5 30.590      no  11.19227 3.713572
## 6 21.565     yes  14.13381 2.890372

Regression model

fit1 <- lm(lnCharges ~ lnAge + bmi + SmokerF,  #Dependent and explanatory variables
           data = mydata4) #Name of the data frame
library(car)
library(png)
  scatterplotMatrix(mydata4[,c(7,8,4)], 
                  smooth= FALSE) 

1.4. Checking mulitcolinearity with VIF

vif(fit1) #Multicolinearity
##    lnAge      bmi  SmokerF 
## 1.005650 1.001150 1.004586
mean(vif(fit1))
## [1] 1.003796

Multicolinearity is not a problem (VIF is close to 1). There is no perfect multicolinearity, as well as also not to strong multicolinearity.

1.5. Checking for outliers and units with high impact

mydata4$StdResid <- round(rstandard(fit1), 3)
mydata4$CooksD <- round(cooks.distance(fit1),3)
#install.packages("png")
library(png)
hist(mydata4$StdResid,
     xlab= "Standard residuals",
     ylab = "Frequency",
     main= "Histogram of standardized residuals")

Standard residuals fall between +/- 3. We will not drop any units. However, we will check if the distiribution of standard residuals is normal.

Shapiro- Wilk normalty test

  • H0: errors are normally distributed.
  • H1: errors are not normally distributed.
shapiro.test(mydata4$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata4$StdResid
## W = 0.97495, p-value = 1.538e-07

We reject H0 (p<0.001). Errors are not normally distributed. However, we will consider it as normal distribution and conclude that because our sample is big enough (499 units), normality is not violated.

With Histogram of Cooks distances we will check, if we have any units with impact.

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

Based on the Histogram we can see, that there are some gaps. Furhermore we will check which are these units with higher values:

head(mydata4[order(-mydata4$CooksD),], 6) #Six units with highest value of Cooks distance
##      ID    charges age    bmi GenderF SmokerF lnCharges    lnAge
## 478 478 3514752.85  24 45.440    Male     yes  15.07248 3.178054
## 193 193 2016733.60  20 45.525  Female     yes  14.51699 2.995732
## 260 260 3516013.46  55 45.530  Female      no  15.07284 4.007333
## 23   23   22144.03  42 30.000    Male     yes  10.00532 3.737670
## 100 100 3461784.06  18 33.535    Male     yes  15.05729 2.890372
## 167 167  224126.48  56 19.950    Male     yes  12.31997 4.025352
##     StdResid CooksD
## 478    2.283  0.022
## 193    2.127  0.021
## 260    2.633  0.016
## 23    -2.091  0.013
## 100    1.820  0.013
## 167   -1.596  0.013

We will remove them:

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:Hmisc':
## 
##     src, summarize
## The following object is masked from 'package:car':
## 
##     recode
## The following objects are masked from 'package:pastecs':
## 
##     first, last
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
mydata4 <- mydata4 %>%
  filter(!ID %in% c(193, 478, 260, 23, 100, 176))

Restimating the regression model

fit1 <- lm(lnCharges ~ lnAge + bmi + SmokerF,  
           data = mydata4)

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

Let’s perform the histograms again:

library(png)
hist(mydata4$StdResid,
     xlab= "Standard residuals",
     ylab = "Frequency",
     main= "Histogram of standardized residuals")

shapiro.test(mydata4$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata4$StdResid
## W = 0.97565, p-value = 2.556e-07

Just in case, we will perform normality test again:

Assumption: the normal distribution of errors

Sapiro- Wilk normalty test

  • H0: errors are normally distributed.
  • H1: errors are not normally distributed. We reject H0 (p<0.001). Errors are not normally distributed. However, as written above we will consider it as normal distribution and conclude that because our sample is big enough (499 units), normality is not violated.
hist(mydata4$CooksD, 
     xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histogram of Cooks distances")

There are no outliers and no gaps anymore, we can continue with our analysis.

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

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

Assumption: Linearity is okay.

Assumption:

However, we will perform Breusch Pagan test for heteroskedasticity

  • H0: the variance is constant
  • H1: the variance is not constant
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 : lnCharges 
##  Variables: fitted values of lnCharges 
## 
##         Test Summary         
##  ----------------------------
##  DF            =    1 
##  Chi2          =    0.3191874 
##  Prob > Chi2   =    0.5720964

We cannot reject H0. We cannot reject homoscedasticity (that the variance is constant).

Assumption: Assumption of error independence is met, because each unit is observed only once, I do not have panel data.

Assumption: The assumption of no.of units being greater than the no. of estimated parameters n>k is met.

Results for regression model

summary(fit1)
## 
## Call:
## lm(formula = lnCharges ~ lnAge + bmi + SmokerF, data = mydata4)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.7845 -1.2327 -0.2932  1.2862  4.6509 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 10.921101   0.758860  14.391  < 2e-16 ***
## lnAge        1.557352   0.189330   8.226 1.77e-15 ***
## bmi         -0.107613   0.009929 -10.839  < 2e-16 ***
## SmokerFno   -1.766032   0.194223  -9.093  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.685 on 489 degrees of freedom
## Multiple R-squared:  0.3428, Adjusted R-squared:  0.3387 
## F-statistic: 85.01 on 3 and 489 DF,  p-value: < 2.2e-16

Partial regression coefficient

H0:beta1 = 0

H1: beta1 =/ 0

BSD we reject H0 at p<0.001, lnAge has a statistically significant effect on charges.

  • lnAge: If Age increased by 1 percentage, then on average Charges increases by 1.56 percentage, holding everything else constant (p < 0.001).

H0:beta1 = 0

H1: beta1 =/ 0

BSD we reject H0 at p<0.001, bmi has a statistically significant effect on charges.

  • bmi: If bmi increases by 1 percentage point, then on average Charges decreases by 10.76 percentage, holding everything alse constant.

H0:beta1 = 0

H1: beta1 =/ 0

BSD we reject H0 at p<0.001, smoking has a statistically significant effect on charges.

  • SmokerFno: Given all other variables, if a person doesn’t’ smoke Charges decreases on average by 83.22 percentage compared if a person smokes.

Multiple R -squared 34.28 percentage of variability of Charges is explained by natural logarithm of age (lnAge), body mass index (bmi) and the smoking factor (SmokingF).

F statistics

H0: beta1 = beta2 = beta3 = 0

H1: At least one is different than 0.

Based on our data we reject H0 (p<0.001) and conclude that at least one of the explanatory variables (lnAge, bmi and smoking) impact charges.

Answer to my research question

Based on our data we found out, that Age, bmi and whether a person smokes or not have a statistically significant influence to the cost of medical insurance premiums charged to an individual by an insurance company.