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
library(boot)
library(broom)
library(lindia)
## Warning: package 'lindia' was built under R version 4.2.3

Import the dataset

data(diamonds)

Dataset overview

dim(diamonds)
## [1] 53940    10
str(diamonds)
## tibble [53,940 × 10] (S3: tbl_df/tbl/data.frame)
##  $ carat  : num [1:53940] 0.23 0.21 0.23 0.29 0.31 0.24 0.24 0.26 0.22 0.23 ...
##  $ cut    : Ord.factor w/ 5 levels "Fair"<"Good"<..: 5 4 2 4 2 3 3 3 1 3 ...
##  $ color  : Ord.factor w/ 7 levels "D"<"E"<"F"<"G"<..: 2 2 2 6 7 7 6 5 2 5 ...
##  $ clarity: Ord.factor w/ 8 levels "I1"<"SI2"<"SI1"<..: 2 3 5 4 2 6 7 3 4 5 ...
##  $ depth  : num [1:53940] 61.5 59.8 56.9 62.4 63.3 62.8 62.3 61.9 65.1 59.4 ...
##  $ table  : num [1:53940] 55 61 65 58 58 57 57 55 61 61 ...
##  $ price  : int [1:53940] 326 326 327 334 335 336 336 337 337 338 ...
##  $ x      : num [1:53940] 3.95 3.89 4.05 4.2 4.34 3.94 3.95 4.07 3.87 4 ...
##  $ y      : num [1:53940] 3.98 3.84 4.07 4.23 4.35 3.96 3.98 4.11 3.78 4.05 ...
##  $ z      : num [1:53940] 2.43 2.31 2.31 2.63 2.75 2.48 2.47 2.53 2.49 2.39 ...
summary(diamonds)
##      carat               cut        color        clarity          depth      
##  Min.   :0.2000   Fair     : 1610   D: 6775   SI1    :13065   Min.   :43.00  
##  1st Qu.:0.4000   Good     : 4906   E: 9797   VS2    :12258   1st Qu.:61.00  
##  Median :0.7000   Very Good:12082   F: 9542   SI2    : 9194   Median :61.80  
##  Mean   :0.7979   Premium  :13791   G:11292   VS1    : 8171   Mean   :61.75  
##  3rd Qu.:1.0400   Ideal    :21551   H: 8304   VVS2   : 5066   3rd Qu.:62.50  
##  Max.   :5.0100                     I: 5422   VVS1   : 3655   Max.   :79.00  
##                                     J: 2808   (Other): 2531                  
##      table           price             x                y         
##  Min.   :43.00   Min.   :  326   Min.   : 0.000   Min.   : 0.000  
##  1st Qu.:56.00   1st Qu.:  950   1st Qu.: 4.710   1st Qu.: 4.720  
##  Median :57.00   Median : 2401   Median : 5.700   Median : 5.710  
##  Mean   :57.46   Mean   : 3933   Mean   : 5.731   Mean   : 5.735  
##  3rd Qu.:59.00   3rd Qu.: 5324   3rd Qu.: 6.540   3rd Qu.: 6.540  
##  Max.   :95.00   Max.   :18823   Max.   :10.740   Max.   :58.900  
##                                                                   
##        z         
##  Min.   : 0.000  
##  1st Qu.: 2.910  
##  Median : 3.530  
##  Mean   : 3.539  
##  3rd Qu.: 4.040  
##  Max.   :31.800  
## 

There are 53940 values and 10 variables in this dataset.

The descriptions of the variables in this dataset are:
Carat: weight of the diamond
Cut: quality of the cut
Color: color of the diamond
Clarity: measurement of how clear the diamond is (I1 worst, SI2, SI1, VS2, VS1, VVS2, VVS1, IF best)
Depth: total depth percentage
Table: width of top of diamond relative to widest point
Price: Price of the diamond in US dollars
X: length in mm
Y: width in mm
Z: depth in mm

The documentation of the variables and their summary statistics are pretty important to get started to perform numerical analysis on the data. The code “str(diamonds)” displays the internal structure of each variable in the dataset.

diamonds %>%
  mutate(carat_group = cut(carat, breaks = seq(0, max(carat) + 0.5, 0.5))) %>%
  group_by(carat_group) %>%
  summarise(mean_price = mean(price))
## # A tibble: 10 × 2
##    carat_group mean_price
##    <fct>            <dbl>
##  1 (0,0.5]           840.
##  2 (0.5,1]          2811.
##  3 (1,1.5]          6514.
##  4 (1.5,2]         11322.
##  5 (2,2.5]         14918.
##  6 (2.5,3]         15473.
##  7 (3,3.5]         14822 
##  8 (3.5,4]         15636.
##  9 (4,4.5]         16576.
## 10 (5,5.5]         18018
diamonds |>
  ggplot(aes(x = carat, fill = cut)) +
  geom_histogram(binwidth = 0.1, position = "dodge") +
  labs(title = "Distribution of Carat by Cut", x = "Carat", y = "Frequency") +
  scale_fill_discrete(name = "Cut") +
  theme_minimal()

The resulting histogram visualizes the distribution of carat values for different cuts. You can observe how the frequency of diamonds varies across different carat ranges for each cut. The dodged bars allow for a direct comparison of carat distributions between different cuts.

This analysis could provide insights into how carat values are distributed within each cut category, helping to understand the characteristics of diamonds in terms of carat size and cut quality.

diamonds |> group_by(cut) |> summarise(mean_depth = mean(depth))
## # A tibble: 5 × 2
##   cut       mean_depth
##   <ord>          <dbl>
## 1 Fair            64.0
## 2 Good            62.4
## 3 Very Good       61.8
## 4 Premium         61.3
## 5 Ideal           61.7
diamonds |> group_by(cut) |> summarise(mean_price = mean(price))
## # A tibble: 5 × 2
##   cut       mean_price
##   <ord>          <dbl>
## 1 Fair           4359.
## 2 Good           3929.
## 3 Very Good      3982.
## 4 Premium        4584.
## 5 Ideal          3458.
diamonds |>
  ggplot(aes(color = cut)) +
  geom_histogram(binwidth = 100, aes(x=price)) +
  labs(title = ("Diamond Price Distribution by Cut"), x = "Diamond Price in $", y = "Frequency") +
  theme_minimal() + 
  facet_wrap(~cut, scales = "free_y")

diamonds |>
  ggplot(aes(x = cut, y = price, fill = cut)) +
  geom_boxplot() + 
  labs(title = "Diamond Price By Cut", x = "Cut Type", y = "Diamond Price in $") +
  theme_minimal() +
  coord_cartesian(ylim=c(0,7500))

The distribution of price by cut is as expected since we just saw the visualization of carat by cut and most of the diamonds are between 0 and 2 carat. We also stated previously that price of diamond has a strong positive correlation with its carat so I’m not surprised the distribution of price is heavily right-skewed.

I just wanted to do a boxplot of the diamond price by cut type to see if it provides better insight than the histogram. I think the boxplot is better to compare diamond price (continuous variable) to its cut quality (categorical variable). Also if I increase the limit on the diamond price there will be a lot more outliers, I chose 7500 in this case to eliminate outliers just for better visualization.

diamonds |>
  group_by(color) |>
  summarise(mean_price = mean(price))
## # A tibble: 7 × 2
##   color mean_price
##   <ord>      <dbl>
## 1 D          3170.
## 2 E          3077.
## 3 F          3725.
## 4 G          3999.
## 5 H          4487.
## 6 I          5092.
## 7 J          5324.
diamonds |>
  ggplot(aes(color = color)) +
  geom_histogram(binwidth = 100, aes(x=price)) +
  labs(title = ("Diamond Price Distribution by Color"), x = "Diamond Price in $", y = "Frequency") +
  theme_minimal() + 
  facet_wrap(~color, scales = "free_y", ncol = 2)

The histogram visualizes how the distribution of diamond prices varies across different colors. Each facet (subplot) represents a different color category. The histogram shows the frequency of diamonds at different price ranges for each color. It helps in understanding the spread and central tendency of prices within each color category. From the above histogram, the distribution of diamond prices are all right-skewed and relatively similar to each other across different color variations. A few noteworthy things to point out is that the Color J has more ‘bumps’ at the $5000 and $10000 marks compared to the other color variations.

diamonds |>
  ggplot(aes(x = clarity, y = price, fill = clarity)) + 
  geom_boxplot() +
  labs(title = "Diamond Price by Clarity", x = "Clarity", y = "Diamond Price in $") + 
  coord_cartesian(ylim=c(0,7500))

Since I think that boxplot is better for visualization. I decided to compare the diamond price using clarity this time. I decided to keep the same price limit and there’s a wider differences between the clarity types compared to cut types. The mean diamond price by cut type varies a lot less compared to clarity type.

price_cut <- diamonds |>
  group_by(cut) |>
  summarise(expected_prob=n()/nrow(diamonds), 
            mean= mean(price), 
            median=median(price), 
            Q1= quantile(price,0.25),
            Q3= quantile(price,0.75),
            IQR = Q3-Q1)

lowest_prob <- price_cut |>
  filter(expected_prob == min(expected_prob))

price_cut <- price_cut |>
  mutate(tag = ifelse(cut==lowest_prob$cut, "anomaly", ""))

price_cut
## # A tibble: 5 × 8
##   cut       expected_prob  mean median    Q1    Q3   IQR tag      
##   <ord>             <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <chr>    
## 1 Fair             0.0298 4359.  3282  2050. 5206. 3155. "anomaly"
## 2 Good             0.0910 3929.  3050. 1145  5028  3883  ""       
## 3 Very Good        0.224  3982.  2648   912  5373. 4461. ""       
## 4 Premium          0.256  4584.  3185  1046  6296  5250  ""       
## 5 Ideal            0.400  3458.  1810   878  4678. 3800. ""
diamonds |>
  ggplot(aes(x=cut,y=price,color=cut))+
  geom_boxplot()

From the above table, color J appears the least which we already know. However, color I and J have the biggest IQR which means their price distribution will vary more than the other colors. Color H and G have similar IQR values but color H diamonds have higher mean and median values so most diamonds in color G will be lower priced than diamonds with color H. Diamonds with color D, E, and F have similar IQR, mean, and median so their distribution will be similar to each other.

A testable hypothesis is that diamonds become more expensive the higher color quality they are. This can be tested by looking at diamonds grouped by their color and compare their prices.

ggplot(diamonds, aes(x = carat, y = price)) +
  geom_point() +
  labs(title = "Scatter Plot of Carat vs. Price",
       x = "Carat",
       y = "Price in $") +
  theme_minimal()

As expected, on average, the price of diamond goes up as the carat goes up. This fan-shaped pattern may indicate that the variability in diamond prices increases or decreases as carat weight changes. In other words, there may be more dispersion in prices for certain carat weights compared to others.

price_color <- diamonds |>
  group_by(color) |>
  summarise(expected_prob=n()/nrow(diamonds), 
            mean= mean(price), 
            median=median(price), 
            Q1= quantile(price,0.25),
            Q3= quantile(price,0.75),
            IQR = Q3-Q1)

lowest_prob <- price_color |>
  filter(expected_prob == min(expected_prob))

price_color <- price_color |>
  mutate(tag = ifelse(color==lowest_prob$color, "anomaly", ""))

price_color
## # A tibble: 7 × 8
##   color expected_prob  mean median    Q1    Q3   IQR tag      
##   <ord>         <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <chr>    
## 1 D            0.126  3170.  1838   911  4214. 3302. ""       
## 2 E            0.182  3077.  1739   882  4003  3121  ""       
## 3 F            0.177  3725.  2344.  982  4868. 3886. ""       
## 4 G            0.209  3999.  2242   931  6048  5117  ""       
## 5 H            0.154  4487.  3460   984  5980. 4996. ""       
## 6 I            0.101  5092.  3730  1120. 7202. 6081. ""       
## 7 J            0.0521 5324.  4234  1860. 7695  5834. "anomaly"
diamonds |>
  ggplot(aes(x=color,y=price,color=color))+
  geom_boxplot()

From the above table, color J appears the least which we already know. However, color I and J have the biggest IQR which means their price distribution will vary more than the other colors. Color H and G have similar IQR values but color H diamonds have higher mean and median values so most diamonds in color G will be lower priced than diamonds with color H. Diamonds with color D, E, and F have similar IQR, mean, and median so their distribution will be similar to each other.

A testable hypothesis is that diamonds become more expensive the higher color quality they are. This can be tested by looking at diamonds grouped by their color and compare their prices.

Hypothesis testing

After examining the relationship between price and other variables, I’ve decided to come up with two questions to try to explore with the dataset.

  1. if there is a significant difference in the mean price between different cut qualities.
  2. Perform an analysis of variance (ANOVA) to test if there are significant differences in mean prices among diamonds with different clarity levels.

First Hypothesis

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

\[ H_a: \text{The difference in mean price between good and premium quality of cut diamonds is not 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_diff <- (avg_prices$avg_price[2] -
                  avg_prices$avg_price[1])
paste("Observed Difference: ", observed_diff)
## [1] "Observed Difference:  655.393252608099"
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()

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
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.
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}'

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"

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

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.

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.

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.

In conclusion, we reject our null hypothesis because clearly the differences in mean price between different cut qualities are not 0.

Second Hypothesis

\[ H_0: \text{average diamond price is equal across all color quality} \]

\[ H_a: \text{average diamond price is not equal across all color quality} \]

diamonds |>
  ggplot() +
  geom_boxplot(mapping = aes(y = price, x = color)) +
  scale_y_log10(labels = \(x) paste('$', x / 1000, 'K')) +
  annotation_logticks(sides = 'l') +
  labs(x = "Color Of Diamond",
       y = "Log Sales Price (in $1000s)") +
  theme_minimal()

The continuous variable I chose here is the price of diamonds. It’s pretty self explanatory on why prices of diamonds are usually the most value to both buyers and sellers so it’s an easy choice.

The explanatory variable that I expect might influence the response variable (price) is the color of diamonds. From previous data dives, we’ve explored pretty much every relationship between price and other variables so that’s why I chose color here.

m <- aov(price ~ color, data = diamonds)
summary(m)
##                Df    Sum Sq   Mean Sq F value Pr(>F)    
## color           6 2.685e+10 4.475e+09   290.2 <2e-16 ***
## Residuals   53933 8.316e+11 1.542e+07                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Given such a small p-value, and such a large dataset, we can conclude that it is very unlikely the means are all equal, and at least one is different from the rest.

Ultimately, there is not enough evidence to conclude that the average diamond price is equal across all color quality, so it would be safe to assume that we can have different average prices for different color qualities.

Final Question

Which variable, cut or color, influences the price of diamonds more?

# Fit a linear regression model
model <- lm(price ~ cut * color, data = diamonds)

# View the summary of the model
summary(model)
## 
## Call:
## lm(formula = price ~ cut * color, data = diamonds)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
##  -5932  -2678  -1335   1317  16131 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   4213.720     26.804 157.204  < 2e-16 ***
## cut.L         -245.446     71.626  -3.427 0.000611 ***
## cut.Q         -284.713     63.976  -4.450 8.59e-06 ***
## cut.C         -696.010     55.684 -12.499  < 2e-16 ***
## cut^4         -264.915     45.225  -5.858 4.72e-09 ***
## color.L       1794.965     80.693  22.244  < 2e-16 ***
## color.Q        198.033     76.500   2.589 0.009637 ** 
## color.C       -389.802     72.995  -5.340 9.33e-08 ***
## color^4         21.775     69.533   0.313 0.754163    
## color^5       -134.097     64.384  -2.083 0.037278 *  
## color^6         70.570     59.191   1.192 0.233167    
## cut.L:color.L 1048.404    216.028   4.853 1.22e-06 ***
## cut.Q:color.L -396.522    193.005  -2.054 0.039935 *  
## cut.C:color.L -387.099    166.943  -2.319 0.020412 *  
## cut^4:color.L -232.278    135.786  -1.711 0.087158 .  
## cut.L:color.Q    2.013    203.801   0.010 0.992120    
## cut.Q:color.Q  -25.180    182.380  -0.138 0.890193    
## cut.C:color.Q -250.336    159.145  -1.573 0.115723    
## cut^4:color.Q   75.753    130.075   0.582 0.560315    
## cut.L:color.C  481.000    195.144   2.465 0.013710 *  
## cut.Q:color.C   89.252    174.311   0.512 0.608637    
## cut.C:color.C   36.904    151.498   0.244 0.807546    
## cut^4:color.C  -52.987    123.082  -0.430 0.666834    
## cut.L:color^4   38.504    187.289   0.206 0.837114    
## cut.Q:color^4  434.893    166.715   2.609 0.009094 ** 
## cut.C:color^4 -171.337    143.408  -1.195 0.232186    
## cut^4:color^4   66.688    115.153   0.579 0.562505    
## cut.L:color^5 -431.380    171.739  -2.512 0.012013 *  
## cut.Q:color^5  316.995    153.356   2.067 0.038735 *  
## cut.C:color^5 -133.017    134.288  -0.991 0.321918    
## cut^4:color^5    5.014    108.906   0.046 0.963281    
## cut.L:color^6  -28.951    156.901  -0.185 0.853606    
## cut.Q:color^6   86.269    140.335   0.615 0.538732    
## cut.C:color^6 -405.828    124.436  -3.261 0.001110 ** 
## cut^4:color^6  195.670    101.363   1.930 0.053564 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 3901 on 53905 degrees of freedom
## Multiple R-squared:  0.0445, Adjusted R-squared:  0.0439 
## F-statistic: 73.84 on 34 and 53905 DF,  p-value: < 2.2e-16

The coefficients of cut and color range from -264.915 to 4213.720 and -862.177 to 1794.965, respectively. Comparing these ranges, it seems that the coefficients for color have larger magnitudes than those for cut. This suggests that, in the context of the linear regression model, color has a relatively stronger impact on diamond prices compared to cut.

Conclusion

Ultimately, the cut quality and color variation both affect the pricing of diamonds positively. Furthermore, color quality of diamonds have a higher influence on their prices compared to their respective cut qualities. My analysis explores valuable insights into the factors influencing diamond quality and pricing, emphasizing carat, cut, color, and clarity as primary determinants. The findings hold significance for professionals in the diamond industry, offering a nuanced understanding of how specific attributes impact a diamond’s visual appeal and market value. This serves as a foundation for future research and application in the gemological field, contributing to ongoing advancements and a better understanding of diamonds.