library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.0     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.1     ✔ tibble    3.1.8
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the ]8;;http://conflicted.r-lib.org/conflicted package]8;; to force all conflicts to become errors
library(ggplot2)
library(dplyr)
library(ggrepel)
## Warning: package 'ggrepel' was built under R version 4.2.3
library(effsize)
## Warning: package 'effsize' was built under R version 4.2.3
library(pwrss)
## Warning: package 'pwrss' was built under R version 4.2.3
## 
## Attaching package: 'pwrss'
## 
## The following object is masked from 'package:stats':
## 
##     power.t.test
library(boot)
library(broom)
library(lindia)
## Warning: package 'lindia' was built under R version 4.2.3
library(vcd)
## Warning: package 'vcd' was built under R version 4.2.3
## Loading required package: grid

Binary Variable

n the diamonds dataset, a column that can be reasonably converted into a binary variable is the clarity column. The clarity column represents the clarity of the diamond and has several levels, ranging from “I1” (worst) to “IF” (best). You can convert this column into a binary variable where diamonds with clarity “IF” are considered high clarity (1) and all other clarity levels are considered not high clarity (0).

# Convert clarity into a binary variable (1 for "IF" clarity, 0 for other clarity level)
diamonds <- diamonds %>%
  mutate(high_clarity = ifelse(clarity == "IF", 1, 0))
# View the modified dataset with the new binary variable
#head(diamonds)

Logistic Regression Model

model <- glm(high_clarity ~ carat + cut + color, 
             data = diamonds, family = binomial)

summary(model)
## 
## Call:
## glm(formula = high_clarity ~ carat + cut + color, family = binomial, 
##     data = diamonds)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -0.6421  -0.2866  -0.1836  -0.1152   3.8970  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -2.69732    0.09364 -28.805  < 2e-16 ***
## carat       -2.17085    0.08976 -24.186  < 2e-16 ***
## cut.L        1.16358    0.21753   5.349 8.84e-08 ***
## cut.Q        0.04492    0.18654   0.241 0.809701    
## cut.C        0.50856    0.13759   3.696 0.000219 ***
## cut^4        0.24778    0.08921   2.777 0.005480 ** 
## color.L      1.13976    0.11612   9.815  < 2e-16 ***
## color.Q     -1.13809    0.10622 -10.715  < 2e-16 ***
## color.C      0.11041    0.09563   1.155 0.248249    
## color^4      0.48083    0.08291   5.799 6.65e-09 ***
## color^5     -0.22670    0.07049  -3.216 0.001300 ** 
## color^6     -0.06485    0.05337  -1.215 0.224319    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 15712  on 53939  degrees of freedom
## Residual deviance: 13763  on 53928  degrees of freedom
## AIC: 13787
## 
## Number of Fisher Scoring iterations: 7

Intercept = -2.69732: When all the other explanatory variables are zero, the log odd of a diamond being high clarity is approximately -2.7. This might not be meaningful in the context of diamonds because diamonds always have other properties.

Carat = -2.17085: For each one unit increase in carat, the log-odds of the diamond being high clarity decreases by approximately 2.17. Larger diamonds are typically less likely to have high clarity because larger diamonds tend to have lower clarity due to the natural formation process of diamonds..

Cut categories: Each cut category have a different coefficient. Each coefficient represents the influence of that subgroup of cut quality compared to the whole category.

Color categories: Similar to cut categories, each color category have a different coefficient. Each coefficient represents the influence of that subgroup of color compared to the whole category.

I’m choosing carat to build my confidence interval

# Calculate confidence interval
lower_bound <- (-2.17085) - (qnorm(0.975) * 0.08976)
upper_bound <- (-2.17085) + (qnorm(0.975) * 0.08976)

# Print the confidence interval
cat("95% Confidence Interval for the Coefficient of carat: [", 
    lower_bound, ",", upper_bound, "]\n")
## 95% Confidence Interval for the Coefficient of carat: [ -2.346776 , -1.994924 ]

We can confidently state that increasing the carat size of a diamond leads to a decrease in the likelihood of high clarity. While the exact impact lies within the range of [−2.346776,−1.994924], it’s clear that larger diamonds are significantly associated with lower clarity in the dataset. The negative values across the interval imply a negative correlation between carat size and high clarity, suggesting that, on average, larger diamonds are less likely to have high clarity compared to smaller ones in the logistic regression model.

Transformation

# Scatter plot for carat vs price
ggplot(diamonds, aes(x = carat, y = price)) +
  geom_point(color = "skyblue", alpha = 0.6) +
  labs(x = "Carat", y = "Price", title = "Scatter Plot: Carat vs Price") +
  theme_minimal()

ggplot(diamonds, aes(x = cut, y = price)) +
  geom_boxplot(fill = "skyblue", color = "black", width = 0.5) +
  labs(x = "Cut", y = "Price", title = "Box Plot: Cut vs Price") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Since the carat vs price scatterplot shows signs of heteroscedasticity, it is reasonable to consider the Box-Cox transformation.

diamonds <- diamonds |>
  mutate(log_price = log(price))

diamonds |> 
  ggplot(mapping = aes(x = carat, y = log_price)) +
  geom_point(shape = 'O', size = 3) +
  geom_smooth(se = FALSE) +
  labs(title = " Carat vs. Log(Price)") +
  theme_minimal()
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

This also looks a bit like a \(y = \sqrt{x}\) function, so we might want to apply a square root transformation to the caratvariable.

diamonds <- diamonds |>
  mutate(sqrt_carat = sqrt(carat))  # add new variable

diamonds |>
  ggplot(mapping = aes(x = sqrt_carat, y = log_price)) +
  geom_point(shape = 'O', size = 3) +
  geom_smooth(se = FALSE) +
  labs(title = "Log(price) vs. sqrt(Carat)") +
  theme_minimal()
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

By looking at the transformation above, it makes sense to transform the carat variable because the relationship is monotonic.