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)

Sepal Width Only Linear Model

# Fitting Linear Model to test differences among species
model_lm <- lm(value ~ Species,
                data = Sepal_data)
# LM Results
summary(model_lm)
## 
## Call:
## lm(formula = value ~ Species, data = Sepal_data)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -1.128 -0.228  0.026  0.226  0.972 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)        3.42800    0.04804  71.359  < 2e-16 ***
## Speciesversicolor -0.65800    0.06794  -9.685  < 2e-16 ***
## Speciesvirginica  -0.45400    0.06794  -6.683 4.54e-10 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3397 on 147 degrees of freedom
## Multiple R-squared:  0.4008, Adjusted R-squared:  0.3926 
## F-statistic: 49.16 on 2 and 147 DF,  p-value: < 2.2e-16
# Test model
anova(model_lm)
## Analysis of Variance Table
## 
## Response: value
##            Df Sum Sq Mean Sq F value    Pr(>F)    
## Species     2 11.345  5.6725   49.16 < 2.2e-16 ***
## Residuals 147 16.962  0.1154                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Plot Sepal LM
plot(model_lm)

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

Which Provides The Best Fit: Untransformed, log(width), sqrt(width)

# Untransformed Model
model2_lmm <- lmer(value ~ structure * Species + (1 | ID), data = Sepal_Petal, REML = FALSE)

# Log-transformed Model
model2_lmm_log <- lmer(log(value) ~ structure * Species + (1 | ID), data = Sepal_Petal, REML = FALSE)

# Square-root-transformed Model
model2_lmm_sqrt <- lmer(sqrt(value) ~ structure * Species + (1 | ID), data = Sepal_Petal, REML = FALSE)

# Calculate AIC for the 3 models
AIC(model2_lmm, model2_lmm_log, model2_lmm_sqrt)
##                 df        AIC
## model2_lmm       8   69.92039
## model2_lmm_log   8 -103.50893
## model2_lmm_sqrt  8 -578.70164
# Plot models to check scatter/variance
plot(model2_lmm)

plot(model2_lmm_log)

plot(model2_lmm_sqrt)

# Calculate ICC
icc(model2_lmm)
## # Intraclass Correlation Coefficient
## 
##     Adjusted ICC: 0.416
##   Unadjusted ICC: 0.026
# Calculate marginal and conditional R2
r2_nakagawa(model2_lmm)
## # R2 for Mixed Models
## 
##   Conditional R2: 0.964
##      Marginal R2: 0.938

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