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(vcd)
## Warning: package 'vcd' was built under R version 4.2.3
## Loading required package: grid

Hypotheses

First Null Hypothesis

\[ H_0: \text{The difference in mean price between good and premium quality of cut diamonds is 0.} \]

Alpha Level: 0.05

Historically, the alpha level of 0.05 is found to be the most effective and reasonable to balance between type I and type II error and it is the commonly accepted in many fields.

Power Level: 85% This indicates an 85% chance of detecting a significant difference if there is one. I’m not too sure on how to pick a good power level so I just followed the one in the lecture for now.

Minimum effect size: $500

A $500 price difference might be considered practically significant. This was determined based on last week’s data dive. There was a graph of price based on different cut quality and I eyeballed the difference between the cut quality to be approximately $500.

Neyman-Pearson hypothesis test.

I believe I have enough data in my dataset to perform a Neyman-Pearson hypothesis test.

\[ H_a: \text{The difference in mean price between good and premium quality of cut diamonds is not equal to 0.} \]

# the same bootstrapping function from lab_06
bootstrap <- function (x, func=mean, n_iter=10^4) {
  # empty vector to be filled with values from each iteration
  func_values <- c(NULL)
  
  # we simulate sampling `n_iter` times
  for (i in 1:n_iter) {
    # pull the sample (e.g., a vector or data frame)
    x_sample <- sample_n(x, size = length(x), replace = TRUE)
    
    # add on this iteration's value to the collection
    func_values <- c(func_values, func(x_sample))
  }
  
  return(func_values)
}
avg_prices <- diamonds |>
  filter(cut %in% c("Good", "Premium")) |>
  group_by(cut) |>
  summarize(avg_price = mean(price)) |>
  arrange(cut)
  
avg_prices
## # A tibble: 2 × 2
##   cut     avg_price
##   <ord>       <dbl>
## 1 Good        3929.
## 2 Premium     4584.

Observed Difference

observed_diff <- (avg_prices$avg_price[2] -
                  avg_prices$avg_price[1])
paste("Observed Difference: ", observed_diff)
## [1] "Observed Difference:  655.393252608099"

Now to calculate the difference in the means

diff_in_avg <- function (x_data) {
  avg_prices <- x_data |>
    group_by(cut) |>
    summarize(avg_price = mean(price)) |>
    arrange(cut)
  
  # difference = revenue_with - revenue_without
  diff <- (avg_prices$avg_price[2] - avg_prices$avg_price[1])
  
  return(diff)
}

diffs_in_avgs <- bootstrap(diamonds, diff_in_avg, n_iter = 100)
ggplot() +
  geom_function(xlim = c(-300, 300), 
                fun = function(x) dnorm(x, mean = 0, 
                                        sd = sd(diffs_in_avgs))) +
  geom_vline(mapping = aes(xintercept = observed_diff,
                           color = paste("observed: ",
                                         round(observed_diff)))) +
  labs(title = "Bootstrapped Sampling Distribution of Price Differences",
       x = "Difference in Price Calculated",
       y = "Probability Density",
       color = "") +
  scale_x_continuous(breaks = seq(-1000, 1000, 100)) +
  theme_minimal()

In our bootstrapped sampling distribution, most of the samples have the difference in price between -300 and 300 so our observed price difference of 655 is very extreme.

Effect Size

cohen.d(d = filter(diamonds, cut == 'Good') |> pluck("price"),
        f = filter(diamonds, cut == 'Premium') |> pluck("price"))
## 
## Cohen's d
## 
## d estimate: -0.1566292 (negligible)
## 95 percent confidence interval:
##      lower      upper 
## -0.1892515 -0.1240068
Visualization
diamonds |>
  filter(cut %in% c("Good", "Premium")) |>
  group_by(cut) |>
  summarize(sd = sd(price),
            mean = mean(price))
## # A tibble: 2 × 3
##   cut        sd  mean
##   <ord>   <dbl> <dbl>
## 1 Good    3682. 3929.
## 2 Premium 4349. 4584.

These standard deviations are roughly equal, so we can just use the whole dataset to approximate the overall value.

test <- pwrss.t.2means(mu1 = 100, 
                       sd1 = sd(pluck(diamonds, "price")),
                       kappa = 1,
                       power = .85, alpha = 0.05, 
                       alternative = "not equal")
##  Difference between Two means 
##  (Independent Samples t Test) 
##  H0: mu1 = mu2 
##  HA: mu1 != mu2 
##  ------------------------------ 
##   Statistical power = 0.85 
##   n1 = 28581 
##   n2 = 28581 
##  ------------------------------ 
##  Alternative = "not equal" 
##  Degrees of freedom = 57160 
##  Non-centrality parameter = 2.996 
##  Type I error rate = 0.05 
##  Type II error rate = 0.15
plot(test)
## Warning in qt(1 - prob.extreme, df = df, ncp = ncp, lower.tail = TRUE): full
## precision may not have been achieved in 'pnt{final}'

P-value
diffs_in_avgs_d <- diffs_in_avgs - mean(diffs_in_avgs)

paste("p-value ", 
      sum(observed_diff < diffs_in_avgs_d) / length(diffs_in_avgs_d))
## [1] "p-value  0"

So, we say “assuming the display ad has no effect on revenue, then 0 of 100 samples this large would yield a difference in revenue of 655.4 or more.”

This makes sense because from our bootstrapped sampling distribution, the difference in price are far away from our observed value.

Fisher’s style Test

Unfortunately, since the hypothesis I made isn’t between two categorical variables so I can’t perform a Fisher’s style test. I can’t perform a test of difference of price (continuous).

Second Null Hypothesis

\[ H_0: \text{There is no association between the cut quality and the diamond color.} \]

Chi-square Test

contingency_table <- table(diamonds$cut, diamonds$cut)

contingency_table
##            
##              Fair  Good Very Good Premium Ideal
##   Fair       1610     0         0       0     0
##   Good          0  4906         0       0     0
##   Very Good     0     0     12082       0     0
##   Premium       0     0         0   13791     0
##   Ideal         0     0         0       0 21551
result <- chisq.test(contingency_table)

result
## 
##  Pearson's Chi-squared test
## 
## data:  contingency_table
## X-squared = 215760, df = 16, p-value < 2.2e-16

Since the p-value is very small (less than the significant level of our chosen value of 0.1), we reject the null hypothesis.

Visualization for the Chi-square test
# Extract observed and expected frequencies from the chi-square test result
observed <- as.vector(result$observed)
expected <- as.vector(result$expected)

# Reshape the data for plotting
data <- data.frame(
  cut = factor(rep(rownames(result$observed), each = ncol(result$observed))),
  color = factor(rep(colnames(result$observed), times = nrow(result$observed))),
  observed = result$observed,
  expected = result$expected
)
## Warning in data.frame(cut = factor(rep(rownames(result$observed), each =
## ncol(result$observed))), : row names were found from a short variable and have
## been discarded
# Create a bar plot
ggplot(data, aes(x = cut, y = observed, fill = color)) +
  geom_bar(stat = "identity", position = "dodge", color = "black") +
  geom_text(aes(label = ifelse(observed != expected, sprintf("%.1f", observed), "")),
            position = position_dodge(width = 0.9), vjust = -0.5) +
  labs(title = "Observed vs. Expected Frequencies",
       x = "Cut",
       y = "Frequency",
       fill = "Color") +
  scale_fill_manual(values = c("#F8766D", "#00BFC4", "#FFC400", "#7CAE00", "#B90000"),
                    labels = c("J", "I", "H", "G", "F")) +  # Set legend labels here
  theme_minimal()

I believe this box plot shows the best visualization for the null hypothesis. Since we rejected the null hypothesis, there’s a certain association between cut and color and the box plot demonstrates this. There’s more diamonds with Ideal, Premium, and Very Good quality of cut than Good and Fair. Furthermore, there’s more quality cut in a certain color than the others.

Fisher’s Style Test

# Perform Fisher's exact test
fisher_test_result <- fisher.test(contingency_table, simulate.p.value = TRUE, B = 1000)

fisher_test_result
## 
##  Fisher's Exact Test for Count Data with simulated p-value (based on
##  1000 replicates)
## 
## data:  contingency_table
## p-value = 0.000999
## alternative hypothesis: two.sided

Since we have a very low p-value again, we can draw the same conclusion as the Chi-square test we performed above.

# Create a data frame for cut vs color
data <- as.data.frame(table(diamonds$cut, diamonds$color))
colnames(data) <- c("Cut", "Color", "Frequency")

# Create a grouped bar plot
ggplot(data, aes(x = Cut, y = Frequency, fill = Color)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Cut vs Color",
       x = "Cut",
       y = "Frequency",
       fill = "Color") +
  theme_minimal()

I believe a bar plot is best illustrated the Fisher’s style test. As we can see, there’s association between color and cut because some colors have higher frequency in some cut quality than the others. For instance, color G diamonds appear more in Ideal cut than other colors.