#install.packages("readxl")
library(readxl)
mydata <- read_xlsx("~/IMB/MVA/Homework 3/Data3.xlsx")

mydata <- as.data.frame(mydata)
head(mydata)
##   ID Age    BMI Smoker   Charges
## 1  1  19 27.900    yes 16884.924
## 2  2  18 33.770     no  1725.552
## 3  3  28 33.000     no  4449.462
## 4  4  33 22.705     no 21984.471
## 5  5  32 28.880     no  3866.855
## 6  6  31 25.740     no  3756.622

Description:

Source of data: Kaggle’s dataset on Medical Cost Personal Cost Prediction

mydata$SmokerF <- factor(mydata$Smoker,
                         levels = c ("no", "yes"),
                         labels = c ("No", "Yes"))

summary(mydata[c(-1, -4)])
##       Age             BMI           Charges      SmokerF   
##  Min.   :18.00   Min.   :15.96   Min.   : 1122   No :1064  
##  1st Qu.:27.00   1st Qu.:26.30   1st Qu.: 4740   Yes: 274  
##  Median :39.00   Median :30.40   Median : 9382             
##  Mean   :39.21   Mean   :30.66   Mean   :13270             
##  3rd Qu.:51.00   3rd Qu.:34.69   3rd Qu.:16640             
##  Max.   :64.00   Max.   :53.13   Max.   :63770
#Making a random sample of 150 units
set.seed(1) 
mydata <- mydata[sample(nrow(mydata), 150), ]
#Checking for linearity
library(car)
## Loading required package: carData
scatterplotMatrix(mydata[ , c(-1, -4, -6)],
                  smooth = FALSE) 

#Transforming depended variable Charges and explanatory variable Age

mydata$lnCharges <- log(mydata$Charges)
mydata$lnAge <- log(mydata$Age)

head(mydata[colnames(mydata) %in% c("ID", "Age", "BMI", "Charges", "SmokerF", "lnCharges" , "lnAge")] )
##        ID Age    BMI   Charges SmokerF lnCharges    lnAge
## 1017 1017  19 24.605  2709.244      No  7.904425 2.944439
## 679   679  56 36.100 12363.547      No  9.422508 4.025352
## 129   129  32 17.765 32734.186     Yes 10.396175 3.465736
## 930   930  41 34.210  6289.755      No  8.746677 3.713572
## 471   471  27 32.670  2497.038      No  7.822861 3.295837
## 299   299  31 34.390 38746.355     Yes 10.564792 3.433987
library(car)
scatterplotMatrix(mydata[c(7, 8, 3)], 
                  smooth = FALSE)

#Checking for multicollinearity
fit1 <- lm(lnCharges ~ lnAge + BMI + SmokerF, 
           data = mydata)

vif(fit1)
##    lnAge      BMI  SmokerF 
## 1.002539 1.014343 1.012988
#Checking for outliers and units with high influence.
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")

head(mydata[order(-mydata$StdResid),], 5)
##        ID Age    BMI Smoker  Charges SmokerF lnCharges    lnAge
## 1040 1040  19 27.265     no 22493.66      No 10.020989 2.944439
## 355   355  18 38.280     no 14133.04      No  9.556270 2.890372
## 526   526  18 33.880     no 11482.63      No  9.348591 2.890372
## 988   988  45 27.645     no 28340.19      No 10.252036 3.806662
## 912   912  18 31.730    yes 33732.69     Yes 10.426223 2.890372
##      StdResid CooksD
## 1040    5.290  0.227
## 355     4.208  0.183
## 526     3.740  0.119
## 988     3.065  0.033
## 912     2.506  0.094
head(mydata[order(mydata$StdResid),], 5)
##      ID Age   BMI Smoker  Charges SmokerF lnCharges    lnAge StdResid
## 867 867  18 37.29     no 1141.445      No  7.040050 2.890372   -1.950
## 664 664  18 33.66     no 1136.399      No  7.035620 2.890372   -1.910
## 375 375  20 33.33     no 1391.529      No  7.238158 2.995732   -1.742
## 889 889  22 39.50     no 1682.597      No  7.428094 3.091042   -1.665
## 359 359  23 41.91     no 1837.282      No  7.516043 3.135494   -1.627
##     CooksD
## 867  0.037
## 664  0.031
## 375  0.020
## 889  0.022
## 359  0.025
hist(mydata$CooksD, 
     xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histogram of Cooks distances")

head(mydata[order(-mydata$CooksD),], 10)
##        ID Age    BMI Smoker   Charges SmokerF lnCharges    lnAge
## 1040 1040  19 27.265     no 22493.660      No 10.020989 2.944439
## 355   355  18 38.280     no 14133.038      No  9.556270 2.890372
## 526   526  18 33.880     no 11482.635      No  9.348591 2.890372
## 912   912  18 31.730    yes 33732.687     Yes 10.426223 2.890372
## 619   619  19 33.110    yes 34439.856     Yes 10.446970 2.944439
## 378   378  24 40.150    yes 38126.247     Yes 10.548658 3.178054
## 843   843  23 32.780    yes 36021.011     Yes 10.491858 3.135494
## 867   867  18 37.290     no  1141.445      No  7.040050 2.890372
## 988   988  45 27.645     no 28340.189      No 10.252036 3.806662
## 664   664  18 33.660     no  1136.399      No  7.035620 2.890372
##      StdResid CooksD
## 1040    5.290  0.227
## 355     4.208  0.183
## 526     3.740  0.119
## 912     2.506  0.094
## 619     2.362  0.080
## 378     1.771  0.048
## 843     1.848  0.039
## 867    -1.950  0.037
## 988     3.065  0.033
## 664    -1.910  0.031
#Removing units ID 1040, 355, 526, 988.
ids_to_remove <- c(1040, 355, 526, 988)
mydata <- subset(mydata, !(ID %in% ids_to_remove))
#Checking for normality
shapiro.test(mydata$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydata$StdResid
## W = 0.9343, p-value = 2.653e-06
fit2 <- lm(lnCharges ~ lnAge + BMI + SmokerF, 
           data = mydata)

mydata$StdFitted <- scale(fit2$fitted.values)
mydata$StdResid <- round(rstandard(fit2), 3) 

library(car)
scatterplot(y = mydata$StdResid, x = mydata$StdFitted,
            ylab = "Standardized residuals",
            xlab = "Standardized fitted values",
            boxplots = FALSE,
            regLine = FALSE,
            smooth = FALSE)

#Checking for homoskedasticity
library(olsrr)
## 
## Attaching package: 'olsrr'
## The following object is masked from 'package:datasets':
## 
##     rivers
ols_test_breusch_pagan(fit2)
## 
##  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          =    4.105478 
##  Prob > Chi2   =    0.0427445
#Using White's robust standard errors
library(estimatr)
fit_robust <- lm(lnCharges ~ lnAge + BMI + SmokerF,  
                        se_type = "HC1",
                        data = mydata)
## Warning: In lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
##  extra argument 'se_type' will be disregarded
summary(fit_robust)
## 
## Call:
## lm(formula = lnCharges ~ lnAge + BMI + SmokerF, data = mydata, 
##     se_type = "HC1")
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.64475 -0.08715  0.01972  0.11847  1.14372 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 3.165816   0.265800  11.911   <2e-16 ***
## lnAge       1.486878   0.066308  22.424   <2e-16 ***
## BMI         0.004890   0.003909   1.251    0.213    
## SmokerFYes  1.663888   0.060104  27.684   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.2986 on 142 degrees of freedom
## Multiple R-squared:  0.9003, Adjusted R-squared:  0.8982 
## F-statistic: 427.6 on 3 and 142 DF,  p-value: < 2.2e-16