Call packages
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.2.1 ✔ readr 2.2.0
## ✔ forcats 1.0.1 ✔ stringr 1.6.0
## ✔ ggplot2 4.0.3 ✔ tibble 3.3.1
## ✔ lubridate 1.9.5 ✔ tidyr 1.3.2
## ✔ purrr 1.2.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(lme4)
## Warning: package 'lme4' was built under R version 4.6.2
## Loading required package: Matrix
##
## Attaching package: 'Matrix'
##
## The following objects are masked from 'package:tidyr':
##
## expand, pack, unpack
library(lmerTest)
## Warning: package 'lmerTest' was built under R version 4.6.2
##
## Attaching package: 'lmerTest'
##
## The following object is masked from 'package:lme4':
##
## lmer
##
## The following object is masked from 'package:stats':
##
## step
library(ggplot2)
library(plotly)
##
## Attaching package: 'plotly'
##
## The following object is masked from 'package:ggplot2':
##
## last_plot
##
## The following object is masked from 'package:stats':
##
## filter
##
## The following object is masked from 'package:graphics':
##
## layout
library(performance)
## Warning: package 'performance' was built under R version 4.6.2
library(emmeans)
## Warning: package 'emmeans' was built under R version 4.6.2
## Welcome to emmeans.
## Caution: You lose important information if you filter this package's results.
## See '? untidy'
Prepare iris dataset
# Convert iris dataset from wide to narrow form
iris2 <- iris %>%
rownames_to_column("ID") %>%
pivot_longer(
cols = c(Petal.Length,Petal.Width,
Sepal.Length,Sepal.Width),
names_to = c("structure", "metric"),
names_sep = "\\.",
values_to = "value"
)
Variability In Sepal Width
Method 1: Boxplot
# Filter data to include only sepal width values
Sepal_data <- iris2 %>%
filter(structure == "Sepal", metric == "Width")
# Boxplot of Iris' Sepal Widths Binned Together
ggplot(Sepal_data, aes(x = Species, y = value, fill = Species)) +
geom_boxplot() +
scale_fill_manual(values = c("setosa" = "red", "versicolor" = "green", "virginica" = "blue")) +
labs(title = "Variation in Sepal Width Of Iris' Species", x = "Species", y = "Sepal Width (cm)") +
theme_classic()

Method 2: Dotplot
# Scatterplot of Individual Iris' Sepal Widths
Sepal_plotly <-
ggplot(Sepal_data, aes(x = Species, y = value, colour = Species)) +
geom_jitter(width = 0.15, height = 0) +
scale_colour_manual(values = c("setosa" = "red", "versicolor" = "green", "virginica" = "blue"))
labs(title = "Variation in Iris' Sepal Width",
x = "Species",
y = "Sepal Width (cm)") +
theme_minimal()
## NULL
ggplotly(Sepal_plotly)
Linear Mixed Model (Addresses the goal: if sepals and petals differ
in width)
Sepal & Petal Width LMM
# Filtering data to include only sepal and petal width
Sepal_Petal <- iris2 %>%
filter(metric == "Width")
# Fitting Linear Mixed-Effects Model
model2_lmm <- lmer(value ~ structure * Species + (1 | ID), data = Sepal_Petal, REML = FALSE)
# Calculate AIC
AIC(model2_lmm)
## [1] 69.92039
# LMM Results
summary(model2_lmm)
## Linear mixed model fit by maximum likelihood . t-tests use Satterthwaite's
## method [lmerModLmerTest]
## Formula: value ~ structure * Species + (1 | ID)
## Data: Sepal_Petal
##
## AIC BIC logLik -2*log(L) df.resid
## 69.9 99.6 -27.0 53.9 292
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.8298 -0.4736 -0.0161 0.4688 3.0225
##
## Random effects:
## Groups Name Variance Std.Dev.
## ID (Intercept) 0.03206 0.1790
## Residual 0.04501 0.2121
## Number of obs: 300, groups: ID, 150
##
## Fixed effects:
## Estimate Std. Error df t value
## (Intercept) 0.24600 0.03926 255.74648 6.266
## structureSepal 3.18200 0.04243 150.00000 74.995
## Speciesversicolor 1.08000 0.05552 255.74648 19.452
## Speciesvirginica 1.78000 0.05552 255.74648 32.060
## structureSepal:Speciesversicolor -1.73800 0.06000 150.00000 -28.965
## structureSepal:Speciesvirginica -2.23400 0.06000 150.00000 -37.231
## Pr(>|t|)
## (Intercept) 1.56e-09 ***
## structureSepal < 2e-16 ***
## Speciesversicolor < 2e-16 ***
## Speciesvirginica < 2e-16 ***
## structureSepal:Speciesversicolor < 2e-16 ***
## structureSepal:Speciesvirginica < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Correlation of Fixed Effects:
## (Intr) strctS Spcsvrs Spcsvrg strctrSpl:Spcsvrs
## structurSpl -0.540
## Specsvrsclr -0.707 0.382
## Specisvrgnc -0.707 0.382 0.500
## strctrSpl:Spcsvrs 0.382 -0.707 -0.540 -0.270
## strctrSpl:Spcsvrg 0.382 -0.707 -0.270 -0.540 0.500
# Test model
anova(model2_lmm)
## Type III Analysis of Variance Table with Satterthwaite's method
## Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
## structure 258.912 258.912 1 150 5752.84 < 2.2e-16 ***
## Species 9.464 4.732 2 150 105.15 < 2.2e-16 ***
## structure:Species 68.812 34.406 2 150 764.47 < 2.2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Plot Sepal/Petal LMM
plot(model2_lmm)

Decode “//.” in pivot_longer
//. tells pivot_longer() to split the original column names at the
period. It allows column names to be separated in structure and metric.
For example: Sepal.Width separated into Sepal(structure) and
Width(metric)
Two-Way ANOVA
# Two-way ANOVA with structure and species + interaction
Two_Way_ANOVA <- aov(value ~ structure * Species,
data = Sepal_Petal)
# Calculate the AIC
AIC(Two_Way_ANOVA)
## [1] 96.41962
# Two-Way ANOVA results
summary(Two_Way_ANOVA)
## Df Sum Sq Mean Sq F value Pr(>F)
## structure 1 258.91 258.91 3292.6 <2e-16 ***
## Species 2 22.95 11.47 145.9 <2e-16 ***
## structure:Species 2 68.81 34.41 437.5 <2e-16 ***
## Residuals 294 23.12 0.08
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Predicted Table of Species’ Sepal/Petal Width
# Calculate predicted widths for each species and structure
Predicted_Widths <- emmeans(model2_lmm_sqrt, ~ structure * Species)
## Cannot use mode = "kenward-roger" because *pbkrtest* package is not installed
# Convert results into a table
Predicted_Table <- as.data.frame(Predicted_Widths) %>%
# Select columns needed
select(Species, structure, emmean) %>%
# Changes table from long to wide format
pivot_wider(names_from = structure,
values_from = emmean) %>%
# Structures in required order
select(Species, Sepal, Petal)
# Display the table
Predicted_Table
## # A tibble: 3 × 3
## Species Sepal Petal
## <fct> <dbl> <dbl>
## 1 setosa 1.85 0.486
## 2 versicolor 1.66 1.15
## 3 virginica 1.72 1.42