model <- lm(charges ~ age + bmi + children + sex + smoker + region, data = data)
summary(model)
##
## Call:
## lm(formula = charges ~ age + bmi + children + sex + smoker +
## region, data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -11304.9 -2848.1 -982.1 1393.9 29992.8
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -11938.5 987.8 -12.086 < 2e-16 ***
## age 256.9 11.9 21.587 < 2e-16 ***
## bmi 339.2 28.6 11.860 < 2e-16 ***
## children 475.5 137.8 3.451 0.000577 ***
## sexmale -131.3 332.9 -0.394 0.693348
## smokeryes 23848.5 413.1 57.723 < 2e-16 ***
## regionnorthwest -353.0 476.3 -0.741 0.458769
## regionsoutheast -1035.0 478.7 -2.162 0.030782 *
## regionsouthwest -960.0 477.9 -2.009 0.044765 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 6062 on 1329 degrees of freedom
## Multiple R-squared: 0.7509, Adjusted R-squared: 0.7494
## F-statistic: 500.8 on 8 and 1329 DF, p-value: < 2.2e-16
coefs <- summary(model)$coefficients
eq <- paste("Charges = ", round(coefs[1, 1], 2), " + ", round(coefs[2, 1], 2), "*(Age) + ", round(coefs[3, 1], 2), "*(BMI) + ", round(coefs[4, 1], 2), "*(Children) + ...", sep="")
plot(model, which = 1)

# Categorizing BMI into recognizable health categories
data$bmi_category <- cut(data$bmi,
breaks = c(0, 18.5, 24.9, 29.9, Inf),
labels = c("Underweight", "Normal", "Overweight", "Obese"),
include.lowest = TRUE)
# Create the histogram
p <- plot_ly(data, x = ~bmi, color = ~bmi_category, colors = c("#ADD8E6", "#90EE90", "#FFD700", "#FF6347"),
type = "histogram",
histnorm = "percent",
marker = list(line = list(color = '#000000', width = 2))) %>%
layout(title = "Distribution of BMI Categories",
xaxis = list(title = "BMI"),
yaxis = list(title = "Percentage"),
barmode = 'overlay',
hovermode = 'closest')