library(readr)
mydata<- read_delim("diamonds_prices.csv", delim = ";", escape_double = FALSE, trim_ws = TRUE) #IMPORTING THE DATA
## Rows: 53943 Columns: 11
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ";"
## chr (3): cut, color, clarity
## dbl (8): Column1, carat, depth, table, price, x, y, z
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
head(mydata)
## # A tibble: 6 × 11
## Column1 carat cut color clarity depth table price x y z
## <dbl> <dbl> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1 23 Ideal E SI2 615 55 326 395 398 243
## 2 2 21 Premium E SI1 598 61 326 389 384 231
## 3 3 23 Good E VS1 569 65 327 405 407 231
## 4 4 29 Premium I VS2 624 58 334 42 423 263
## 5 5 31 Good J SI2 633 58 335 434 435 275
## 6 6 24 Very Good J VVS2 628 57 336 394 396 248
colnames(mydata)[1] = "ID" #changing the name of the column for better understanding
head (mydata)
## # A tibble: 6 × 11
## ID carat cut color clarity depth table price x y z
## <dbl> <dbl> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1 23 Ideal E SI2 615 55 326 395 398 243
## 2 2 21 Premium E SI1 598 61 326 389 384 231
## 3 3 23 Good E VS1 569 65 327 405 407 231
## 4 4 29 Premium I VS2 624 58 334 42 423 263
## 5 5 31 Good J SI2 633 58 335 434 435 275
## 6 6 24 Very Good J VVS2 628 57 336 394 396 248
https://www.kaggle.com/datasets/nancyalaswad90/diamonds-prices/data
There is no missing values, each column is fully populated.
ID: Index number, used to uniquely identify each row (Numerical)
Carat: Weight of the diamond, measured in carats (Numerical) A carat is a unit of mass equal to 200 mg. The carat weight has a significant impact on the diamond’s price, with higher carat diamonds being generally more expensive, all else being equal.
Cut: Quality of the cut (Ideal, Premium, Good, Very good, Fair) (Categorical) The cut grade assesses how well a diamond has been shaped and how well it reflects light. It’s one of the most important factors in determining a diamond’s beauty and price.
Color: Diamond color, rated from D (best, colorless) to Z (worst, colorful). (categorical) The color grading assesses the absence of color, with less color signifying a higher quality and value.
Clarity: A measurement of how clear the diamond is.(categorical) Higher clarity diamonds have fewer inclusions and are more valuable.
Depth: Total depth percentage = z/ mean (x,y) x 100 (numerical) This metric is important in assessing the quality of the cut, affecting the diamond’s brilliance. Table: Width of the top of the diamond relative to the widest point.(numerical)
Price: Price in US dollars.(numerical)
x: Length in mm.(numerical)
y: Width in mm.(numerical)
z: Depth in mm.(numerical)
“Is there a significant difference in the price of diamonds based on their cut quality?”
This question involves comparing the mean prices of diamonds across different cut qualities. I will test this using both parametric (ANOVA) and non-parametric (Kruskal-Wallis) tests.
Hypothesis - Comparison of three or more arithmetic means for independent samples.
Price - dependent variable Cut - independent varibles (5 variables)
We want to know, how does the price differ, based on the cut of the diamond.
H0: All cuts have the same arithemitc mean of the price H1: At least one arithemitc mean is different.
#DATA
mydata$cutF <- factor (mydata$cut,
levels = c("Fair", "Good", "Very Good", "Premium", "Ideal"),
labels = c ("Fair", "Good", "Very Good", "Premium", "Ideal"))
#Creating a new factor variable cutF, where we turn the categorical variable (cut) in to a factor
#install.packages("psych")
library(psych)
## Warning: package 'psych' was built under R version 4.3.2
summary(mydata$cutF) #what does the variable describe
## Fair Good Very Good Premium Ideal
## 1610 4906 12083 13793 21551
# Comparing independent variable with dependent variables
describeBy(x = mydata$price, group = mydata$cutF)
##
## Descriptive statistics by group
## group: Fair
## vars n mean sd median trimmed mad min max range skew
## X1 1 1610 4358.76 3560.39 3282 3695.65 2183.13 337 18574 18237 1.78
## kurtosis se
## X1 3.07 88.73
## ------------------------------------------------------------
## group: Good
## vars n mean sd median trimmed mad min max range skew
## X1 1 4906 3928.86 3681.59 3050.5 3251.51 2853.26 327 18788 18461 1.72
## kurtosis se
## X1 3.04 52.56
## ------------------------------------------------------------
## group: Very Good
## vars n mean sd median trimmed mad min max range skew
## X1 1 12083 3981.66 3935.72 2649 3243.17 2855.49 336 18818 18482 1.6
## kurtosis se
## X1 2.24 35.8
## ------------------------------------------------------------
## group: Premium
## vars n mean sd median trimmed mad min max range skew
## X1 1 13793 4583.99 4348.95 3183 3822.04 3368.47 326 18823 18497 1.33
## kurtosis se
## X1 1.07 37.03
## ------------------------------------------------------------
## group: Ideal
## vars n mean sd median trimmed mad min max range skew
## X1 1 21551 3457.54 3808.4 1810 2656.14 1630.86 326 18806 18480 1.84
## kurtosis se
## X1 2.98 25.94
We are checking if homoskedasticity is being met.
H0= All variances are the same. H1= At least ONE variance is different.
#install.packages(car)
library(car)
## Loading required package: carData
##
## Attaching package: 'car'
## The following object is masked from 'package:psych':
##
## logit
leveneTest(mydata$price, group = mydata$cutF)
## Levene's Test for Homogeneity of Variance (center = median)
## Df F value Pr(>F)
## group 4 123.46 < 2.2e-16 ***
## 53938
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
We reject H0 at p < 0.001, At least one variance is different.
We are testing if the variables are distributed normally. We need to be carefull that all p values are more than 5%, otherwise we reject H0 (we go to non-parametric tests).
H0: Price is distributed normally for each dependent variable. H1: Price is NOT distributed normally for each dependent variable.
#install.packages("dplyr")
#install.packages("rstatix")
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.3.2
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:car':
##
## recode
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(rstatix)
## Warning: package 'rstatix' was built under R version 4.3.2
##
## Attaching package: 'rstatix'
## The following object is masked from 'package:stats':
##
## filter
#Becaue I have too big of a sample, I made a "sample size". Smple can be big from 1600 (the sample size of "Fair cut", to 5000 (limit for shapiro_test))
sample_size <- 1600
mydata_sampled <- mydata %>%
group_by(cutF) %>%
sample_n(min(sample_size, 5000)) %>%
ungroup()
mydata_sampled %>%
group_by(cutF) %>%
shapiro_test(price)
## # A tibble: 5 × 4
## cutF variable statistic p
## <fct> <chr> <dbl> <dbl>
## 1 Fair price 0.809 7.24e-40
## 2 Good price 0.825 1.17e-38
## 3 Very Good price 0.823 8.18e-39
## 4 Premium price 0.841 2.83e-37
## 5 Ideal price 0.745 3.14e-44
None of the p values are bigger than 5% (p < 0.001), whoch means, we should use non-parametric tests.
We can reject H0, Price is NOT distributed normally for group of dependent variables.
H0: All arihtmeitc means are the same. H1: At least one arithemitc mean is different
ANOVA_res <- aov(price ~ cutF,
data = mydata)
summary(ANOVA_res)
## Df Sum Sq Mean Sq F value Pr(>F)
## cutF 4 1.104e+10 2.759e+09 175.6 <2e-16 ***
## Residuals 53938 8.474e+11 1.571e+07
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
We reject H0 at p<0.001, which means that one of the arithemitc means is different. We can assume that the cut of the diamond affects the price of the diamond.
#install.packages("effectsize")
library(effectsize)
## Warning: package 'effectsize' was built under R version 4.3.2
##
## Attaching package: 'effectsize'
## The following objects are masked from 'package:rstatix':
##
## cohens_d, eta_squared
## The following object is masked from 'package:psych':
##
## phi
eta_squared(ANOVA_res)
## For one-way between subjects designs, partial eta squared is equivalent
## to eta squared. Returning eta squared.
## # Effect Size for ANOVA
##
## Parameter | Eta2 | 95% CI
## -------------------------------
## cutF | 0.01 | [0.01, 1.00]
##
## - One-sided CIs: upper bound fixed at [1.00].
interpret_eta_squared(0.01, rules = "cohen1992")
## [1] "very small"
## (Rules: cohen1992)
We measured the effect size of ANOVA. Effect size is very small, which means that there are very small differences between averages. We can assume that the cut of the ring has a very small effect on the price of the diamond.
We use this test when there the assumption of homogeneity of variances is violated.
Test of arithmetic means.
H0: All arithemitc means are the same. H1: At least one arithemitc mean is different.
#install.packages("onewaytests")
library(onewaytests)
## Warning: package 'onewaytests' was built under R version 4.3.2
##
## Attaching package: 'onewaytests'
## The following object is masked from 'package:psych':
##
## describe
welch.test(price ~ cutF,
data= mydata)
##
## Welch's Heteroscedastic F Test (alpha = 0.05)
## -------------------------------------------------------------
## data : price and cutF
##
## statistic : 165.9927
## num df : 4
## denom df : 9398.687
## p.value : 1.507975e-137
##
## Result : Difference is statistically significant.
## -------------------------------------------------------------
We reject H0 at p <0.001, which means that at least one arithemitc mean is different.
We use bonferroni corrections.
H0: Arithmetic means from all dependent variables are the same H1: At least one is different.
We need to look at p values!
pairwise.t.test(x = mydata$price, g = mydata$cutF,
p.adj = "bonf")
##
## Pairwise comparisons using t tests with pooled SD
##
## data: mydata$price and mydata$cutF
##
## Fair Good Very Good Premium
## Good 0.0016 - - -
## Very Good 0.0034 1.0000 - -
## Premium 0.3096 < 2e-16 < 2e-16 -
## Ideal < 2e-16 5.7e-13 < 2e-16 < 2e-16
##
## P value adjustment method: bonferroni
We found a statistically significant relationship between diamond cut and average price (F = 175.6, p <0.001), The effect size is very small (eta quare = 0.01). Post hoc tests revealed differences for each pari of groups ( p< 0.001).
We do it after the assumption of normality is violated, whohc means that one variable is not normally distributed.
H0 = The location distributions for price are the same in all five groups. H1 = The location distributions for price are NOT the same in all five groups.
kruskal.test(price~cutF,
data = mydata)
##
## Kruskal-Wallis rank sum test
##
## data: price by cutF
## Kruskal-Wallis chi-squared = 978.75, df = 4, p-value < 2.2e-16
kruskal_effsize(price~cutF,
data = mydata)
## # A tibble: 1 × 5
## .y. n effsize method magnitude
## * <chr> <int> <dbl> <chr> <ord>
## 1 price 53943 0.0181 eta2[H] small
H0 = location distributions of Price are the same for all three groups H1 = location distributions of Price are not the same for all three groups
library(rstatix)
groups_nonpar <- wilcox_test (price ~ cutF,
paired = FALSE, #we have independent samples
p.adjust.method = "bonferroni",
data = mydata)
groups_nonpar
## # A tibble: 10 × 9
## .y. group1 group2 n1 n2 statistic p p.adj p.adj.signif
## * <chr> <chr> <chr> <int> <int> <dbl> <dbl> <dbl> <chr>
## 1 price Fair Good 1610 4906 4.44e6 5.55e- 14 5.55e- 13 ****
## 2 price Fair Very … 1610 12083 1.12e7 1.39e- 23 1.39e- 22 ****
## 3 price Fair Premi… 1610 13793 1.18e7 1.34e- 5 1.34e- 4 ***
## 4 price Fair Ideal 1610 21551 2.24e7 3.44e- 86 3.44e- 85 ****
## 5 price Good Very … 4906 12083 3.03e7 2.3 e- 2 2.3 e- 1 ns
## 6 price Good Premi… 4906 13793 3.15e7 1.28e- 12 1.28e- 11 ****
## 7 price Good Ideal 4906 21551 5.93e7 4.20e- 40 4.20e- 39 ****
## 8 price Very Good Premi… 12083 13793 7.59e7 3.54e- 35 3.54e- 34 ****
## 9 price Very Good Ideal 12083 21551 1.41e8 6.63e- 39 6.63e- 38 ****
## 10 price Premium Ideal 13793 21551 1.74e8 6.52e-166 6.52e-165 ****
In this analysis, we explored the relationship between the cut quality of diamonds and their prices. Our primary research question was: “Is there a significant difference in the price of diamonds based on their cut quality?” To answer this, we conducted both parametric (ANOVA) and non-parametric tests (Kruskal-Wallis, Welch’s F-test, Wilcoxon rank sum test) on a dataset of diamond prices and attributes.
ANOVA Test: The results of the ANOVA test indicated a statistically significant difference in diamond prices based on cut quality (F = 175.6, p < 0.001). However, the effect size, as measured by eta squared, was very small (0.01), suggesting that while the cut of the diamond does impact its price, this effect is minimal.
Non-Parametric Tests:
The Kruskal-Wallis test also showed a significant difference in price distributions across different diamond cuts (Chi-square = 978.75, p < 0.001), with a similarly small effect size (eta square = 0.02).
Welch’s F-test and the Wilcoxon rank sum test further supported these findings, indicating significant differences in the arithmetic means and location distributions of diamond prices across different cuts.
These findings imply that while the cut quality of a diamond is a factor in its pricing, it might not be the most influential factor. Other attributes like carat, color, and clarity may play more significant roles in determining a diamond’s price. This insight is valuable for both consumers and sellers in the diamond market.
It is important to note the limitations of our analysis. The small effect sizes observed suggest that the practical significance of cut quality on diamond prices might be limited. Additionally, our analysis did not control for other diamond characteristics, which could confound the observed relationship between cut quality and price.
library(readr)
winedata <- read_csv("Wine_Quality_Data.csv")
## Rows: 6497 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): color
## dbl (12): fixed_acidity, volatile_acidity, citric_acid, residual_sugar, chlo...
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
head(winedata)
## # A tibble: 6 × 13
## fixed_acidity volatile_acidity citric_acid residual_sugar chlorides
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 7.4 0.7 0 1.9 0.076
## 2 7.8 0.88 0 2.6 0.098
## 3 7.8 0.76 0.04 2.3 0.092
## 4 11.2 0.28 0.56 1.9 0.075
## 5 7.4 0.7 0 1.9 0.076
## 6 7.4 0.66 0 1.8 0.075
## # ℹ 8 more variables: free_sulfur_dioxide <dbl>, total_sulfur_dioxide <dbl>,
## # density <dbl>, pH <dbl>, sulphates <dbl>, alcohol <dbl>, quality <dbl>,
## # color <chr>
https://www.kaggle.com/datasets/ghassenkhaled/wine-quality-data
Description of the data set
All variables are numerical, except Color, whoch is cateogorical.
Fixed Acidity (grams per liter): Higher values indicate a more acidic wine, which can affect tartness and taste; lower values mean less acidity and potentially a flatter taste.
Volatile Acidity (grams per liter): Lower values are typical for higher quality wine, as high levels can lead to an unpleasant vinegar taste.
Citric Acid (grams per liter): Higher levels often contribute to the wine’s freshness and flavor, while too much can overpower the natural grape flavors.
Residual Sugar (grams per liter): High levels indicate a sweeter wine; dry wines typically have low residual sugar content.
Chlorides (grams per liter): Lower chloride levels are generally preferred as higher levels can lead to a salty taste, often perceived as a negative quality in wine.
Free Sulfur Dioxide (milligrams per liter): This is about preserving wine and preventing oxidation; both very low and very high levels can be problematic for quality.
Total Sulfur Dioxide (milligrams per liter): It’s used to gauge the wine’s preservative levels; too much can affect the aroma and taste.
Density (grams per cubic centimeter): This relates to the wine’s alcohol and sugar content; higher density can indicate a sweeter or more alcoholic wine.
pH: The scale ranges from 0 to 14; most wines are between 3 and 4. Lower pH means higher acidity, which can make the wine taste sharper.
Sulphates (grams per liter): Used as an additive to prevent microbial growth; higher levels can contribute to the wine’s longevity and possibly its tanginess.
Alcohol (% by volume): Indicates the alcohol content; higher percentages usually mean a stronger, more robust wine, while lower percentages can lead to a lighter taste.
Quality (scale of 3-9 in this dataset): A subjective score reflecting the overall perceived quality of the wine, with higher scores indicating better quality.
Color: Categorized simply as red or white, this reflects the type of grapes used and the production method, which fundamentally affects the wine’s character and flavor profile
What physicochemical properties of wine most significantly influence its quality?
summary(winedata)
## fixed_acidity volatile_acidity citric_acid residual_sugar
## Min. : 3.800 Min. :0.0800 Min. :0.0000 Min. : 0.600
## 1st Qu.: 6.400 1st Qu.:0.2300 1st Qu.:0.2500 1st Qu.: 1.800
## Median : 7.000 Median :0.2900 Median :0.3100 Median : 3.000
## Mean : 7.215 Mean :0.3397 Mean :0.3186 Mean : 5.443
## 3rd Qu.: 7.700 3rd Qu.:0.4000 3rd Qu.:0.3900 3rd Qu.: 8.100
## Max. :15.900 Max. :1.5800 Max. :1.6600 Max. :65.800
## chlorides free_sulfur_dioxide total_sulfur_dioxide density
## Min. :0.00900 Min. : 1.00 Min. : 6.0 Min. :0.9871
## 1st Qu.:0.03800 1st Qu.: 17.00 1st Qu.: 77.0 1st Qu.:0.9923
## Median :0.04700 Median : 29.00 Median :118.0 Median :0.9949
## Mean :0.05603 Mean : 30.53 Mean :115.7 Mean :0.9947
## 3rd Qu.:0.06500 3rd Qu.: 41.00 3rd Qu.:156.0 3rd Qu.:0.9970
## Max. :0.61100 Max. :289.00 Max. :440.0 Max. :1.0390
## pH sulphates alcohol quality
## Min. :2.720 Min. :0.2200 Min. : 8.00 Min. :3.000
## 1st Qu.:3.110 1st Qu.:0.4300 1st Qu.: 9.50 1st Qu.:5.000
## Median :3.210 Median :0.5100 Median :10.30 Median :6.000
## Mean :3.219 Mean :0.5313 Mean :10.49 Mean :5.818
## 3rd Qu.:3.320 3rd Qu.:0.6000 3rd Qu.:11.30 3rd Qu.:6.000
## Max. :4.010 Max. :2.0000 Max. :14.90 Max. :9.000
## color
## Length:6497
## Class :character
## Mode :character
##
##
##
library (pastecs)
##
## Attaching package: 'pastecs'
## The following objects are masked from 'package:dplyr':
##
## first, last
round(stat.desc(winedata[-13]),2) #we removed color, since it is categorical
## fixed_acidity volatile_acidity citric_acid residual_sugar
## nbr.val 6497.00 6497.00 6497.00 6497.00
## nbr.null 0.00 0.00 151.00 0.00
## nbr.na 0.00 0.00 0.00 0.00
## min 3.80 0.08 0.00 0.60
## max 15.90 1.58 1.66 65.80
## range 12.10 1.50 1.66 65.20
## sum 46877.85 2206.81 2070.16 35364.70
## median 7.00 0.29 0.31 3.00
## mean 7.22 0.34 0.32 5.44
## SE.mean 0.02 0.00 0.00 0.06
## CI.mean.0.95 0.03 0.00 0.00 0.12
## var 1.68 0.03 0.02 22.64
## std.dev 1.30 0.16 0.15 4.76
## coef.var 0.18 0.48 0.46 0.87
## chlorides free_sulfur_dioxide total_sulfur_dioxide density
## nbr.val 6497.00 6497.00 6497.00 6497.00
## nbr.null 0.00 0.00 0.00 0.00
## nbr.na 0.00 0.00 0.00 0.00
## min 0.01 1.00 6.00 0.99
## max 0.61 289.00 440.00 1.04
## range 0.60 288.00 434.00 0.05
## sum 364.05 198323.00 751992.50 6462.54
## median 0.05 29.00 118.00 0.99
## mean 0.06 30.53 115.74 0.99
## SE.mean 0.00 0.22 0.70 0.00
## CI.mean.0.95 0.00 0.43 1.37 0.00
## var 0.00 315.04 3194.72 0.00
## std.dev 0.04 17.75 56.52 0.00
## coef.var 0.63 0.58 0.49 0.00
## pH sulphates alcohol quality
## nbr.val 6497.00 6497.00 6497.00 6497.00
## nbr.null 0.00 0.00 0.00 0.00
## nbr.na 0.00 0.00 0.00 0.00
## min 2.72 0.22 8.00 3.00
## max 4.01 2.00 14.90 9.00
## range 1.29 1.78 6.90 6.00
## sum 20910.60 3451.65 68165.23 37802.00
## median 3.21 0.51 10.30 6.00
## mean 3.22 0.53 10.49 5.82
## SE.mean 0.00 0.00 0.01 0.01
## CI.mean.0.95 0.00 0.00 0.03 0.02
## var 0.03 0.02 1.42 0.76
## std.dev 0.16 0.15 1.19 0.87
## coef.var 0.05 0.28 0.11 0.15
library(car)
scatterplotMatrix(winedata[ , c(-13)],
smooth = FALSE)
#install.packages("Hmisc")
library(Hmisc)
## Warning: package 'Hmisc' was built under R version 4.3.2
##
## Attaching package: 'Hmisc'
## The following object is masked from 'package:onewaytests':
##
## describe
## The following objects are masked from 'package:dplyr':
##
## src, summarize
## The following object is masked from 'package:psych':
##
## describe
## The following objects are masked from 'package:base':
##
## format.pval, units
rcorr(as.matrix(winedata[, c(-13)]))
## fixed_acidity volatile_acidity citric_acid residual_sugar
## fixed_acidity 1.00 0.22 0.32 -0.11
## volatile_acidity 0.22 1.00 -0.38 -0.20
## citric_acid 0.32 -0.38 1.00 0.14
## residual_sugar -0.11 -0.20 0.14 1.00
## chlorides 0.30 0.38 0.04 -0.13
## free_sulfur_dioxide -0.28 -0.35 0.13 0.40
## total_sulfur_dioxide -0.33 -0.41 0.20 0.50
## density 0.46 0.27 0.10 0.55
## pH -0.25 0.26 -0.33 -0.27
## sulphates 0.30 0.23 0.06 -0.19
## alcohol -0.10 -0.04 -0.01 -0.36
## quality -0.08 -0.27 0.09 -0.04
## chlorides free_sulfur_dioxide total_sulfur_dioxide density
## fixed_acidity 0.30 -0.28 -0.33 0.46
## volatile_acidity 0.38 -0.35 -0.41 0.27
## citric_acid 0.04 0.13 0.20 0.10
## residual_sugar -0.13 0.40 0.50 0.55
## chlorides 1.00 -0.20 -0.28 0.36
## free_sulfur_dioxide -0.20 1.00 0.72 0.03
## total_sulfur_dioxide -0.28 0.72 1.00 0.03
## density 0.36 0.03 0.03 1.00
## pH 0.04 -0.15 -0.24 0.01
## sulphates 0.40 -0.19 -0.28 0.26
## alcohol -0.26 -0.18 -0.27 -0.69
## quality -0.20 0.06 -0.04 -0.31
## pH sulphates alcohol quality
## fixed_acidity -0.25 0.30 -0.10 -0.08
## volatile_acidity 0.26 0.23 -0.04 -0.27
## citric_acid -0.33 0.06 -0.01 0.09
## residual_sugar -0.27 -0.19 -0.36 -0.04
## chlorides 0.04 0.40 -0.26 -0.20
## free_sulfur_dioxide -0.15 -0.19 -0.18 0.06
## total_sulfur_dioxide -0.24 -0.28 -0.27 -0.04
## density 0.01 0.26 -0.69 -0.31
## pH 1.00 0.19 0.12 0.02
## sulphates 0.19 1.00 0.00 0.04
## alcohol 0.12 0.00 1.00 0.44
## quality 0.02 0.04 0.44 1.00
##
## n= 6497
##
##
## P
## fixed_acidity volatile_acidity citric_acid residual_sugar
## fixed_acidity 0.0000 0.0000 0.0000
## volatile_acidity 0.0000 0.0000 0.0000
## citric_acid 0.0000 0.0000 0.0000
## residual_sugar 0.0000 0.0000 0.0000
## chlorides 0.0000 0.0000 0.0017 0.0000
## free_sulfur_dioxide 0.0000 0.0000 0.0000 0.0000
## total_sulfur_dioxide 0.0000 0.0000 0.0000 0.0000
## density 0.0000 0.0000 0.0000 0.0000
## pH 0.0000 0.0000 0.0000 0.0000
## sulphates 0.0000 0.0000 0.0000 0.0000
## alcohol 0.0000 0.0024 0.3977 0.0000
## quality 0.0000 0.0000 0.0000 0.0029
## chlorides free_sulfur_dioxide total_sulfur_dioxide density
## fixed_acidity 0.0000 0.0000 0.0000 0.0000
## volatile_acidity 0.0000 0.0000 0.0000 0.0000
## citric_acid 0.0017 0.0000 0.0000 0.0000
## residual_sugar 0.0000 0.0000 0.0000 0.0000
## chlorides 0.0000 0.0000 0.0000
## free_sulfur_dioxide 0.0000 0.0000 0.0382
## total_sulfur_dioxide 0.0000 0.0000 0.0090
## density 0.0000 0.0382 0.0090
## pH 0.0003 0.0000 0.0000 0.3463
## sulphates 0.0000 0.0000 0.0000 0.0000
## alcohol 0.0000 0.0000 0.0000 0.0000
## quality 0.0000 0.0000 0.0008 0.0000
## pH sulphates alcohol quality
## fixed_acidity 0.0000 0.0000 0.0000 0.0000
## volatile_acidity 0.0000 0.0000 0.0024 0.0000
## citric_acid 0.0000 0.0000 0.3977 0.0000
## residual_sugar 0.0000 0.0000 0.0000 0.0029
## chlorides 0.0003 0.0000 0.0000 0.0000
## free_sulfur_dioxide 0.0000 0.0000 0.0000 0.0000
## total_sulfur_dioxide 0.0000 0.0000 0.0000 0.0008
## density 0.3463 0.0000 0.0000 0.0000
## pH 0.0000 0.0000 0.1159
## sulphates 0.0000 0.8071 0.0019
## alcohol 0.0000 0.8071 0.0000
## quality 0.1159 0.0019 0.0000
Alcohol and Quality: There is a strong positive correlation between alcohol and wine quality (correlation coefficient = 0.44), which is statistically significant (p < 0.001). This suggests that wines with higher alcohol content tend to have higher quality ratings.
Density and Alcohol: A strong negative correlation exists between density and alcohol (correlation coefficient = -0.69), which is also statistically significant (p < 0.001). This implies that wines with higher alcohol content tend to be less dense.
Free Sulfur Dioxide and Total Sulfur Dioxide: These two variables have a high positive correlation (correlation coefficient = 0.72), indicating that wines with higher amounts of free sulfur dioxide also tend to have higher total sulfur dioxide levels.
Acidity Relationships:
Fixed Acidity and Citric Acid: A moderate positive correlation (correlation coefficient = 0.32), suggesting that wines with higher fixed acidity also tend to have higher levels of citric acid.
Volatile Acidity and Citric Acid: A moderate negative correlation (correlation coefficient = -0.38), indicating that higher volatile acidity is associated with lower citric acid levels.
Sulphates and Chlorides: There is a positive correlation between sulphates and chlorides (correlation coefficient = 0.40), suggesting that wines with higher sulphate levels also tend to have higher chloride levels.
Residual Sugar and Total Sulfur Dioxide: A positive correlation (correlation coefficient = 0.50) suggests that wines with higher residual sugar content also tend to have higher total sulfur dioxide levels.
Volatile Acidity and Quality: A negative correlation (correlation coefficient = -0.27) implies that higher volatile acidity is associated with lower wine quality, which is statistically significant.
The statistical significance of these correlations (p-values) supports the reliability of these findings. These correlations provide valuable insights into how different chemical properties interact and influence the overall quality of wine. For instance, the significant relationship between alcohol content and quality could be particularly relevant for wine producers aiming to optimize the quality of their products.
fit1 <- lm (quality ~ alcohol + sulphates + pH + density + total_sulfur_dioxide + fixed_acidity + volatile_acidity + citric_acid + chlorides + free_sulfur_dioxide + total_sulfur_dioxide,
data = winedata)
#creating a linear model
library(car)
vif(fit1) #testing the multicolinearity
## alcohol sulphates pH
## 2.601616 1.376819 1.479788
## density total_sulfur_dioxide fixed_acidity
## 3.326900 2.762037 2.327640
## volatile_acidity citric_acid chlorides
## 1.786058 1.607439 1.549899
## free_sulfur_dioxide
## 2.130044
mean(vif(fit1)) #the average should be close to 1 as possible
## [1] 2.094824
Standardized residuals
Looking for outlires
#making a new variables with standardized residuals
winedata$stdresid <- round (rstandard(fit1), 3)
#making a new variable with cooks distances
winedata$cooksd <- round (cooks.distance(fit1), 3)
hist(winedata$stdresid,
xlab = "standarized residuals",
ylab = "frequency",
main = "Histogram of standarized residuals")
Graph has a lot of outlires (everything more than +/-3 is considered an outlier.)
Testing if standard residuals are normally distributed.
H0: Standard errors are normally distributed. H1: Standard errors are not normally distributed.
#Because I have too big of a sample, I made a "sample size".
sample_small <- sample(nrow(winedata), 5000)
# Creating a smaller dataset
winedata_small <- winedata[sample_small, ]
fit2 <- lm(quality ~ alcohol + sulphates + pH + density + total_sulfur_dioxide + fixed_acidity + volatile_acidity + citric_acid + chlorides + free_sulfur_dioxide + total_sulfur_dioxide,
data = winedata_small)
winedata_small$stdresid <- round (rstandard(fit2), 3)
winedata_small$cooksd <- round (cooks.distance(fit2), 3)
shapiro.test(winedata_small$stdresid)
##
## Shapiro-Wilk normality test
##
## data: winedata_small$stdresid
## W = 0.99033, p-value < 2.2e-16
We reject H0 at p<0.001, therefore we can assume that the errors are not normally distributed.
Since we have a really big sample, this is not a big deal.
summary(winedata_small$cooksd)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.0000000 0.0000000 0.0000000 0.0001758 0.0000000 0.1650000
hist(winedata$cooksd,
xlab = "cooks distance",
ylab = "frequency",
main = "Histogram of Cooks distances")
winedata$stdfit <- scale (fit1$fitted.values)
library(car)
scatterplot (y = winedata$stdresid, x= winedata$stdfit,
ylab = "Std residuals",
xlab = "std fitted values",
boxplot = FALSE,
regLine = FALSE,
smooth = FALSE)
There is some linearity.
We can assume that the assumption of homoskedasticity is violated.
#I wanted to run ols_test_breusch_pagan, but I couldn't find the olsrr library.
#I also did not find lm beta library, therefore my analysis is not totaly complete, but I did what I could.
summary (fit1) #results of regression model
##
## Call:
## lm(formula = quality ~ alcohol + sulphates + pH + density + total_sulfur_dioxide +
## fixed_acidity + volatile_acidity + citric_acid + chlorides +
## free_sulfur_dioxide + total_sulfur_dioxide, data = winedata)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.9885 -0.4659 -0.0389 0.4664 3.1373
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -3.331e+01 5.535e+00 -6.018 1.86e-09 ***
## alcohol 3.625e-01 1.240e-02 29.219 < 2e-16 ***
## sulphates 5.580e-01 7.233e-02 7.715 1.39e-14 ***
## pH -5.351e-02 6.940e-02 -0.771 0.440719
## density 3.623e+01 5.579e+00 6.494 9.00e-11 ***
## total_sulfur_dioxide -1.910e-03 2.697e-04 -7.081 1.58e-12 ***
## fixed_acidity -2.762e-02 1.079e-02 -2.558 0.010537 *
## volatile_acidity -1.517e+00 7.446e-02 -20.375 < 2e-16 ***
## citric_acid -9.483e-02 8.003e-02 -1.185 0.236069
## chlorides -1.114e+00 3.260e-01 -3.417 0.000636 ***
## free_sulfur_dioxide 6.290e-03 7.542e-04 8.340 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.7393 on 6486 degrees of freedom
## Multiple R-squared: 0.2843, Adjusted R-squared: 0.2832
## F-statistic: 257.7 on 10 and 6486 DF, p-value: < 2.2e-16
- H0: rho = 0 (coefficinet of the determination) or Non of the variables cannot explain the differences in wine quality
- H1: rho > 0 or Some of the varaibles can explain the wine quality.
Multiple r2 (coefficient of the determination) = 0.2843
28,43% of the wine quality can be explained by the linear effect of the varibles.
pH and cistric acid are not statically significant.
- If average alcohol increases by 1 procentage point , the quality of wine on average goes UP by 0.365 point (p < 0.001). Assuming all other variables remain UNCHANGED.
sqrt(summary(fit1)$r.squared) #coefficient of the multiple correlation
## [1] 0.5332407
Linear relationship betweenquality and other explanatory varibles is semi strong.
#we made a dummy varible
winedata$colorF <- factor(winedata$color,
levels = c("red", "white"),
labels = c("0", "1"))
fit3 <- lm(quality ~ alcohol + sulphates + pH + density + total_sulfur_dioxide + fixed_acidity + volatile_acidity + citric_acid + chlorides + free_sulfur_dioxide + total_sulfur_dioxide + color,
data = winedata)
summary(fit3)
##
## Call:
## lm(formula = quality ~ alcohol + sulphates + pH + density + total_sulfur_dioxide +
## fixed_acidity + volatile_acidity + citric_acid + chlorides +
## free_sulfur_dioxide + total_sulfur_dioxide + color, data = winedata)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.0100 -0.4666 -0.0380 0.4669 3.1536
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -3.150e+01 5.715e+00 -5.512 3.68e-08 ***
## alcohol 3.619e-01 1.241e-02 29.163 < 2e-16 ***
## sulphates 5.341e-01 7.475e-02 7.144 1.00e-12 ***
## pH -8.036e-02 7.255e-02 -1.108 0.268047
## density 3.459e+01 5.727e+00 6.040 1.63e-09 ***
## total_sulfur_dioxide -1.679e-03 3.253e-04 -5.160 2.54e-07 ***
## fixed_acidity -3.178e-02 1.128e-02 -2.817 0.004858 **
## volatile_acidity -1.560e+00 8.178e-02 -19.077 < 2e-16 ***
## citric_acid -8.552e-02 8.036e-02 -1.064 0.287275
## chlorides -1.209e+00 3.345e-01 -3.615 0.000302 ***
## free_sulfur_dioxide 6.134e-03 7.641e-04 8.028 1.17e-15 ***
## colorwhite -6.294e-02 4.957e-02 -1.270 0.204242
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.7393 on 6485 degrees of freedom
## Multiple R-squared: 0.2845, Adjusted R-squared: 0.2833
## F-statistic: 234.4 on 11 and 6485 DF, p-value: < 2.2e-16
Data did not change a lot, which means that the dummy variable does not have a big impact. Color is not statistically significant in the model, which means, that the color of the wine does not have an effect on the quality.
Other data did not change a lot.
We can statistically check which model is better for this data. H0: DELTA RO SQUARE = 0 (the differences in the determination coefficients), both models are equally good H1: delta ro square > 0, model 2 is better than model 1
anova (fit1, fit3) #we compare the two regression models
## Analysis of Variance Table
##
## Model 1: quality ~ alcohol + sulphates + pH + density + total_sulfur_dioxide +
## fixed_acidity + volatile_acidity + citric_acid + chlorides +
## free_sulfur_dioxide + total_sulfur_dioxide
## Model 2: quality ~ alcohol + sulphates + pH + density + total_sulfur_dioxide +
## fixed_acidity + volatile_acidity + citric_acid + chlorides +
## free_sulfur_dioxide + total_sulfur_dioxide + color
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 6486 3545.1
## 2 6485 3544.2 1 0.88106 1.6121 0.2042
We do not reject H0 atp = 0.2, which means that models are equally good.
winedata$fitted <- fitted.values (fit3)
winedata$residuals <- residuals (fit3)
#selection of the variables
head (winedata[colnames(winedata) %in% c("alcohol", "chlorides", "total_sulfur_dioxide")] )
## # A tibble: 6 × 3
## chlorides total_sulfur_dioxide alcohol
## <dbl> <dbl> <dbl>
## 1 0.076 34 9.4
## 2 0.098 67 9.8
## 3 0.092 54 9.8
## 4 0.075 60 9.8
## 5 0.076 34 9.4
## 6 0.075 40 9.4
This analysis of the Wine Quality Dataset via linear regression reveals critical insights into the determinants of wine quality. Our model, encompassing a broad spectrum of physicochemical properties, highlighted significant predictors of wine quality. Notably, alcohol content emerged as a crucial factor, where a 1 percentage point increase in alcohol content elevates the wine quality score by approximately 0.365 points (p < 0.001), assuming other variables remain constant. Conversely, pH and citric acid were found to be statistically insignificant, indicating a minimal direct impact on wine quality.
Residual analysis uncovered the presence of outliers, as evident from the standardized residuals and Cook’s distance, signaling exceptional cases in the dataset. The Shapiro-Wilk test performed on a subset (n=5000) indicated that the residuals are not normally distributed (p < 0.001), but given the large sample size of our dataset, this deviation is not likely to significantly undermine the model’s robustness.
A particularly interesting aspect of our analysis was the examination of wine color’s influence on quality. Introducing a dummy variable for color revealed that color does not significantly impact the model’s predictions, suggesting that chemical composition rather than color predominantly determines wine quality.
Further, an ANOVA comparison between the models with and without the color variable showed no significant improvement in the model’s explanatory power (p = 0.2), confirming that the inclusion of wine color as a variable does not enhance the model’s ability to predict wine quality.
In conclusion, my analysis shows that 28.43% of the variation in wine quality can be explained by the linear effect of the variables studied. These insights provide valuable guidance for wine producers and enthusiasts, emphasizing the chemical qualities that are most influential in determining the perceived quality of wine.