#Data source: https://www.kaggle.com/datasets/thedevastator/prediction-of-insurance-charges-using-age-gender?select=insurance.csv
library(openxlsx)
setwd("C:/Users/Korisnik/Desktop/RMT")
Insurance_data <- read.xlsx("Insurance.xlsx")

Insurance_data$sex <- as.factor(Insurance_data$sex)
Insurance_data$smoker <- as.factor(Insurance_data$smoker)

#creating dummy variables without intercepts for each dummy variable
Region_dummy <- model.matrix(~ region - 1, data = Insurance_data)
#renaming the dummy variables
colnames(Region_dummy) <- gsub("region", "", colnames(Region_dummy))
#adding the dummy variables to the BankData dataset
Insurance_data <- cbind(Insurance_data, Region_dummy)

head(Insurance_data)
##   index age    sex    bmi children smoker    region   charges northeast
## 1     0  19 female 27.900        0    yes southwest 16884.924         0
## 2     1  18   male 33.770        1     no southeast  1725.552         0
## 3     2  28   male 33.000        3     no southeast  4449.462         0
## 4     3  33   male 22.705        0     no northwest 21984.471         0
## 5     4  32   male 28.880        0     no northwest  3866.855         0
## 6     5  31 female 25.740        0     no southeast  3756.622         0
##   northwest southeast southwest
## 1         0         0         1
## 2         0         1         0
## 3         0         1         0
## 4         1         0         0
## 5         1         0         0
## 6         0         1         0
library(psych)
describe(Insurance_data)
##           vars    n     mean       sd  median  trimmed     mad     min      max
## index        1 1338   668.50   386.39  668.50   668.50  495.93    0.00  1337.00
## age          2 1338    39.21    14.05   39.00    39.01   17.79   18.00    64.00
## sex*         3 1338     1.51     0.50    2.00     1.51    0.00    1.00     2.00
## bmi          4 1338    30.66     6.10   30.40    30.50    6.20   15.96    53.13
## children     5 1338     1.09     1.21    1.00     0.94    1.48    0.00     5.00
## smoker*      6 1338     1.20     0.40    1.00     1.13    0.00    1.00     2.00
## region*      7 1338     2.52     1.10    3.00     2.52    1.48    1.00     4.00
## charges      8 1338 13270.42 12110.01 9382.03 11076.02 7440.81 1121.87 63770.43
## northeast    9 1338     0.24     0.43    0.00     0.18    0.00    0.00     1.00
## northwest   10 1338     0.24     0.43    0.00     0.18    0.00    0.00     1.00
## southeast   11 1338     0.27     0.45    0.00     0.22    0.00    0.00     1.00
## southwest   12 1338     0.24     0.43    0.00     0.18    0.00    0.00     1.00
##              range  skew kurtosis     se
## index      1337.00  0.00    -1.20  10.56
## age          46.00  0.06    -1.25   0.38
## sex*          1.00 -0.02    -2.00   0.01
## bmi          37.17  0.28    -0.06   0.17
## children      5.00  0.94     0.19   0.03
## smoker*       1.00  1.46     0.14   0.01
## region*       3.00 -0.04    -1.33   0.03
## charges   62648.55  1.51     1.59 331.07
## northeast     1.00  1.20    -0.55   0.01
## northwest     1.00  1.20    -0.57   0.01
## southeast     1.00  1.02    -0.95   0.01
## southwest     1.00  1.20    -0.57   0.01
summary(Insurance_data)
##      index             age            sex           bmi           children    
##  Min.   :   0.0   Min.   :18.00   female:662   Min.   :15.96   Min.   :0.000  
##  1st Qu.: 334.2   1st Qu.:27.00   male  :676   1st Qu.:26.30   1st Qu.:0.000  
##  Median : 668.5   Median :39.00                Median :30.40   Median :1.000  
##  Mean   : 668.5   Mean   :39.21                Mean   :30.66   Mean   :1.095  
##  3rd Qu.:1002.8   3rd Qu.:51.00                3rd Qu.:34.69   3rd Qu.:2.000  
##  Max.   :1337.0   Max.   :64.00                Max.   :53.13   Max.   :5.000  
##  smoker        region             charges        northeast     
##  no :1064   Length:1338        Min.   : 1122   Min.   :0.0000  
##  yes: 274   Class :character   1st Qu.: 4740   1st Qu.:0.0000  
##             Mode  :character   Median : 9382   Median :0.0000  
##                                Mean   :13270   Mean   :0.2422  
##                                3rd Qu.:16640   3rd Qu.:0.0000  
##                                Max.   :63770   Max.   :1.0000  
##    northwest        southeast       southwest     
##  Min.   :0.0000   Min.   :0.000   Min.   :0.0000  
##  1st Qu.:0.0000   1st Qu.:0.000   1st Qu.:0.0000  
##  Median :0.0000   Median :0.000   Median :0.0000  
##  Mean   :0.2429   Mean   :0.272   Mean   :0.2429  
##  3rd Qu.:0.0000   3rd Qu.:1.000   3rd Qu.:0.0000  
##  Max.   :1.0000   Max.   :1.000   Max.   :1.0000
#according to the descriptive statistics:
#the sample size is 1338 units, 8 original variables and 4 additional dummy variables
#all distributions are normal upon reviewing the small skewness and kurtosis values
#there is equal distribution of ages according to the quartiles, ranging from 18 to 64 years (working age) 
#there is approximately equal number of men and women in the sample
#there is equal distribution of sample units across all 4 of the regions, with southeast being slightly more populated (27%) than the rest (24%)

#research question 1: Is there a significant difference in BMI index scores between smokers and non-smokers?

describeBy(Insurance_data$bmi, g = Insurance_data$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
library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
ggplot(Insurance_data, aes(x = bmi)) +
  geom_histogram(binwidth = 5, colour="gray") +
  facet_wrap(~smoker, ncol = 1) +
  ylab("Frequency")

library(car)
## Warning: package 'car' was built under R version 4.0.4
## Loading required package: carData
## Warning: package 'carData' was built under R version 4.0.5
## 
## Attaching package: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
leveneTest(Insurance_data$bmi, group = Insurance_data$smoker)
## Levene's Test for Homogeneity of Variance (center = median)
##         Df F value Pr(>F)
## group    1  1.1973 0.2741
##       1336
#Levene's test is not statistically significant (p>0.05), meaning that the homoskedasticity assumption is not violated

library(rstatix)
## 
## Attaching package: 'rstatix'
## The following object is masked from 'package:stats':
## 
##     filter
Insurance_data %>%
  group_by(smoker) %>%
  shapiro_test(bmi)
## # A tibble: 2 x 4
##   smoker variable statistic        p
##   <fct>  <chr>        <dbl>    <dbl>
## 1 no     bmi          0.994 0.000422
## 2 yes    bmi          0.991 0.0852
#Shapiro-Wilk test of normality indicates that the distribution of non-smokers is not normal (p<0.05), while the distribution of smokers is normal
#however, upon investigating the histograms, it seems that the non-smokers are also normally distributed and that the Shapiro-Wilk was just sensitive to the sample size

t.test(Insurance_data$bmi ~ Insurance_data$smoker,
       paired = FALSE,
       var.equal = TRUE,
       alternative = "two.sided")
## 
##  Two Sample t-test
## 
## data:  Insurance_data$bmi by Insurance_data$smoker
## t = -0.13708, df = 1336, p-value = 0.891
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -0.8673980  0.7540904
## sample estimates:
##  mean in group no mean in group yes 
##          30.65180          30.70845
#t-test with the value of -0.13708 is not statistically significant (p>0.05)

library(effectsize)
## 
## Attaching package: 'effectsize'
## The following objects are masked from 'package:rstatix':
## 
##     cohens_d, eta_squared
## The following object is masked from 'package:psych':
## 
##     phi
effectsize::cohens_d(Insurance_data$bmi ~ Insurance_data$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)
#effect size of CohenD -9.16e-03 is tiny

wilcox.test(Insurance_data$bmi ~ Insurance_data$smoker,
            paired = FALSE,
            correct = FALSE,
            exact = FALSE,
            alternative = "two.sided")
## 
##  Wilcoxon rank sum test
## 
## data:  Insurance_data$bmi by Insurance_data$smoker
## W = 145309, p-value = 0.9358
## alternative hypothesis: true location shift is not equal to 0
#Wilcoxon Ranked Sum Test is non-significant as well (p>0.05)

effectsize(wilcox.test(Insurance_data$bmi ~ Insurance_data$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)
#effect size of biserial correlation -3.15e-03 is tiny

#Results = given that neither the homoskedasticity nor normality of distribution assumptions are violated, we can go with the independent t-test instead of non-parametric alternative - however, in both cases the test is non-significant meaning that there is no significant difference in BMI values between the smokers and non-smokers

#research question 2: which of the following variables (age, sex, bmi, number of children, smoker, region) are relevant for insurance rate charges?

Sex_dummy <- model.matrix(~ sex - 1, data = Insurance_data)
colnames(Sex_dummy) <- gsub("sex", "", colnames(Sex_dummy))
Insurance_data <- cbind(Insurance_data, Sex_dummy)

Smoker_dummy <- model.matrix(~ smoker - 1, data = Insurance_data)
colnames(Smoker_dummy) <- gsub("smoker", "", colnames(Smoker_dummy))
Insurance_data <- cbind(Insurance_data, Smoker_dummy)

#additional dummy variables for gender and smoking were added

head(Insurance_data)
##   index age    sex    bmi children smoker    region   charges northeast
## 1     0  19 female 27.900        0    yes southwest 16884.924         0
## 2     1  18   male 33.770        1     no southeast  1725.552         0
## 3     2  28   male 33.000        3     no southeast  4449.462         0
## 4     3  33   male 22.705        0     no northwest 21984.471         0
## 5     4  32   male 28.880        0     no northwest  3866.855         0
## 6     5  31 female 25.740        0     no southeast  3756.622         0
##   northwest southeast southwest female male no yes
## 1         0         0         1      1    0  0   1
## 2         0         1         0      0    1  1   0
## 3         0         1         0      0    1  1   0
## 4         1         0         0      0    1  1   0
## 5         1         0         0      0    1  1   0
## 6         0         1         0      1    0  1   0
data_regression <- Insurance_data[ , c("age", "bmi", "children", "charges", "northeast", "northwest", "southeast", "southwest", "female", "male", "no", "yes")]

scatterplotMatrix(data_regression,
                  smooth = FALSE)

#scatterplots indicate that out of the numeric variables, "children" and "charges" should be winsorized

quantile(Insurance_data$children, 0.95)
## 95% 
##   3
Insurance_data$children_W <- ifelse(test = Insurance_data$children > 3,
                                   yes = 3,
                                   no = Insurance_data$children)

par(mfrow = c(1, 2))
hist(Insurance_data$children,
     main = "Number of children")
hist(Insurance_data$children_W,
     main = "Number of children (W)")

quantile(Insurance_data$charges, 0.95)
##      95% 
## 41181.83
Insurance_data$charges_W <- ifelse(test = Insurance_data$charges > 41181.83,
                                    yes = 41181.83,
                                    no = Insurance_data$charges)

par(mfrow = c(1, 2))
hist(Insurance_data$charges,
     main = "Number of children")
hist(Insurance_data$charges_W,
     main = "Number of children (W)")

fit <- lm(charges_W ~ age + bmi + children_W + northeast + northwest + southeast + male + yes,
          data = Insurance_data)

vif(fit)
##        age        bmi children_W  northeast  northwest  southeast       male 
##   1.017806   1.106791   1.006041   1.525715   1.525253   1.596789   1.008789 
##        yes 
##   1.012570
#variance inflation factor (vif) values are low, indicating the absence of any multicolinearity

Insurance_data$StdResid <- round(rstandard(fit), 3)
Insurance_data$CooksD <- round(cooks.distance(fit), 3)

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

shapiro.test(Insurance_data$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  Insurance_data$StdResid
## W = 0.88702, p-value < 2.2e-16
hist(Insurance_data$CooksD,
     xlab = "Cook's distances",
     ylab = "Frequency",
     main = "Histogram of Cook's distances")

head(Insurance_data[order(Insurance_data$StdResid), c("index", "StdResid")], 5)
##      index StdResid
## 100     99   -1.874
## 413    412   -1.872
## 1101  1100   -1.857
## 381    380   -1.856
## 267    266   -1.824
head(Insurance_data[order(-Insurance_data$StdResid), c("index", "StdResid")], 5)
##      index StdResid
## 243    242    4.347
## 220    219    4.186
## 517    516    4.116
## 1207  1206    3.975
## 937    936    3.874
head(Insurance_data[order(-Insurance_data$CooksD), c("index", "CooksD")], 5)
##      index CooksD
## 220    219  0.014
## 1013  1012  0.013
## 1028  1027  0.012
## 243    242  0.011
## 1207  1206  0.011
outliers <- which(Insurance_data$StdResid > 3 | Insurance_data$StdResid < -3)
print(outliers)
##  [1]    4   10   63  103  116  141  220  243  322  388  431  469  517  527  600
## [16]  689  937  988 1009 1013 1020 1028 1040 1143 1207 1329
#there are 26 observations whose standardized residuals are above 3 and should thus be considered as outliers

influential_obs <- which(Insurance_data$CooksD > 1)
print(influential_obs)
## integer(0)
#there are no influential points according to the Cook's distance

Insurance_data <- Insurance_data[-outliers, ]

#the outliers have been removed from the sample

fit <- lm(charges_W ~ age + bmi + children_W + northeast + northwest + southeast + male + yes,
          data = Insurance_data)

Insurance_data$StdFitted <- scale(fit$fitted.values)

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

#scatterplot of standardized fitted values and standardized residuals indicates that the heteroskedasticity is definitely present

library(olsrr)
## Warning: package 'olsrr' was built under R version 4.0.5
## 
## 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 : charges_W 
##  Variables: fitted values of charges_W 
## 
##          Test Summary           
##  -------------------------------
##  DF            =    1 
##  Chi2          =    306.3342 
##  Prob > Chi2   =    1.373473e-68
#Breusch-Pagan test is statistically significant (p<0.05) confirming the presence of heteroskedasticity

library(Hmisc)
## Warning: package 'Hmisc' was built under R version 4.0.4
## Loading required package: lattice
## Loading required package: survival
## Loading required package: Formula
## 
## Attaching package: 'Hmisc'
## The following object is masked from 'package:psych':
## 
##     describe
## The following objects are masked from 'package:base':
## 
##     format.pval, units
rcorr(as.matrix(Insurance_data[c("charges_W", "age", "bmi", "children_W", "northeast", "northwest", "southeast", "southwest", "male", "female", "yes", "no")],
                type = "pearson"))
##            charges_W   age   bmi children_W northeast northwest southeast
## charges_W       1.00  0.30  0.20       0.08      0.01     -0.05      0.08
## age             0.30  1.00  0.11       0.05      0.01      0.00     -0.01
## bmi             0.20  0.11  1.00       0.01     -0.14     -0.13      0.27
## children_W      0.08  0.05  0.01       1.00     -0.03      0.04     -0.02
## northeast       0.01  0.01 -0.14      -0.03      1.00     -0.32     -0.35
## northwest      -0.05  0.00 -0.13       0.04     -0.32      1.00     -0.35
## southeast       0.08 -0.01  0.27      -0.02     -0.35     -0.35      1.00
## southwest      -0.04  0.01 -0.01       0.01     -0.32     -0.32     -0.35
## male            0.06 -0.02  0.05       0.02      0.00     -0.01      0.02
## female         -0.06  0.02 -0.05      -0.02      0.00      0.01     -0.02
## yes             0.82 -0.03  0.00       0.02      0.00     -0.03      0.07
## no             -0.82  0.03  0.00      -0.02      0.00      0.03     -0.07
##            southwest  male female   yes    no
## charges_W      -0.04  0.06  -0.06  0.82 -0.82
## age             0.01 -0.02   0.02 -0.03  0.03
## bmi            -0.01  0.05  -0.05  0.00  0.00
## children_W      0.01  0.02  -0.02  0.02 -0.02
## northeast      -0.32  0.00   0.00  0.00  0.00
## northwest      -0.32 -0.01   0.01 -0.03  0.03
## southeast      -0.35  0.02  -0.02  0.07 -0.07
## southwest       1.00  0.00   0.00 -0.04  0.04
## male            0.00  1.00  -1.00  0.08 -0.08
## female          0.00 -1.00   1.00 -0.08  0.08
## yes            -0.04  0.08  -0.08  1.00 -1.00
## no              0.04 -0.08   0.08 -1.00  1.00
## 
## n= 1312 
## 
## 
## P
##            charges_W age    bmi    children_W northeast northwest southeast
## charges_W            0.0000 0.0000 0.0027     0.7255    0.0771    0.0051   
## age        0.0000           0.0000 0.0487     0.7598    0.9763    0.6332   
## bmi        0.0000    0.0000        0.6294     0.0000    0.0000    0.0000   
## children_W 0.0027    0.0487 0.6294            0.3343    0.1656    0.3845   
## northeast  0.7255    0.7598 0.0000 0.3343               0.0000    0.0000   
## northwest  0.0771    0.9763 0.0000 0.1656     0.0000              0.0000   
## southeast  0.0051    0.6332 0.0000 0.3845     0.0000    0.0000             
## southwest  0.1349    0.8253 0.7044 0.6272     0.0000    0.0000    0.0000   
## male       0.0185    0.4900 0.0771 0.5275     0.8802    0.6363    0.4941   
## female     0.0185    0.4900 0.0771 0.5275     0.8802    0.6363    0.4941   
## yes        0.0000    0.3377 0.9712 0.4056     0.8732    0.2161    0.0160   
## no         0.0000    0.3377 0.9712 0.4056     0.8732    0.2161    0.0160   
##            southwest male   female yes    no    
## charges_W  0.1349    0.0185 0.0185 0.0000 0.0000
## age        0.8253    0.4900 0.4900 0.3377 0.3377
## bmi        0.7044    0.0771 0.0771 0.9712 0.9712
## children_W 0.6272    0.5275 0.5275 0.4056 0.4056
## northeast  0.0000    0.8802 0.8802 0.8732 0.8732
## northwest  0.0000    0.6363 0.6363 0.2161 0.2161
## southeast  0.0000    0.4941 0.4941 0.0160 0.0160
## southwest            0.9282 0.9282 0.1535 0.1535
## male       0.9282           0.0000 0.0062 0.0062
## female     0.9282    0.0000        0.0062 0.0062
## yes        0.1535    0.0062 0.0062        0.0000
## no         0.1535    0.0062 0.0062 0.0000
#the correlation matrix shows, among other information, that the dependent variable 'charges_W' is significantly correlated with age, BMI index, number of children, southeastern region, both gender and smoking

summary(fit)
## 
## Call:
## lm(formula = charges_W ~ age + bmi + children_W + northeast + 
##     northwest + southeast + male + yes, data = Insurance_data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -10456.9  -2317.0   -543.5   1641.9  17192.7 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -12133.20     833.30 -14.560  < 2e-16 ***
## age            244.13       9.77  24.988  < 2e-16 ***
## bmi            319.44      23.34  13.689  < 2e-16 ***
## children_W     461.53     123.69   3.731 0.000199 ***
## northeast      750.87     390.58   1.922 0.054770 .  
## northwest      209.26     390.64   0.536 0.592269    
## southeast     -176.11     383.49  -0.459 0.646148    
## male           -16.02     272.30  -0.059 0.953094    
## yes          22984.52     335.50  68.507  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4909 on 1303 degrees of freedom
## Multiple R-squared:  0.8113, Adjusted R-squared:  0.8101 
## F-statistic: 700.2 on 8 and 1303 DF,  p-value: < 2.2e-16
library(estimatr)

fit1 <- lm_robust(charges_W ~ age + bmi + children_W + northeast + northwest + southeast + male + yes,
                  se_type = "HC1",
                  data = Insurance_data)

#the correction had to be performed due to the evident presence of heteroskedasticity

summary(fit1)
## 
## Call:
## lm_robust(formula = charges_W ~ age + bmi + children_W + northeast + 
##     northwest + southeast + male + yes, data = Insurance_data, 
##     se_type = "HC1")
## 
## Standard error type:  HC1 
## 
## Coefficients:
##              Estimate Std. Error   t value   Pr(>|t|)   CI Lower CI Upper   DF
## (Intercept) -12133.20    826.753 -14.67573  3.047e-45 -13755.111 -10511.3 1303
## age            244.13      9.392  25.99454 2.342e-120    225.709    262.6 1303
## bmi            319.44     26.015  12.27890  7.140e-33    268.402    370.5 1303
## children_W     461.53    121.265   3.80594  1.478e-04    223.632    699.4 1303
## northeast      750.87    383.755   1.95663  5.060e-02     -1.978   1503.7 1303
## northwest      209.26    363.619   0.57549  5.651e-01   -504.084    922.6 1303
## southeast     -176.11    389.540  -0.45210  6.513e-01   -940.303    588.1 1303
## male           -16.02    270.668  -0.05919  9.528e-01   -547.012    515.0 1303
## yes          22984.52    482.324  47.65366 9.098e-288  22038.306  23930.7 1303
## 
## Multiple R-squared:  0.8113 ,    Adjusted R-squared:  0.8101 
## F-statistic: 544.6 on 8 and 1303 DF,  p-value: < 2.2e-16
#the regression function indicates that the following predictors are statistically significant for the 'charges_W' dependent variable: age, bmi, children_W and smoking (p<0.05)

sqrt(summary(fit1)$r.squared)
## [1] 0.9007191
#Results = the coefficient of correlation is 0.901, while the correlation of determination is 0.811 and statistically significant (p<0.05), meaning that 81.1% of variance of insurance charges can be explained with this model - in particular, insurance buyers that are older, with higher BMI index, smokers and that have more children will be charged more for their life insurance policies