<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yps Henu on Medium]]></title>
        <description><![CDATA[Stories by Yps Henu on Medium]]></description>
        <link>https://medium.com/@yps.henu?source=rss-cb36c3a909a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cg25wDn7WI1IdSDb</url>
            <title>Stories by Yps Henu on Medium</title>
            <link>https://medium.com/@yps.henu?source=rss-cb36c3a909a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:16:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yps.henu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Calculate Species Diversity in R: Richness, Shannon, Simpson & Hill Numbers]]></title>
            <link>https://medium.com/@yps.henu/how-to-calculate-species-diversity-in-r-richness-shannon-simpson-hill-numbers-3817657dbb9f?source=rss-cb36c3a909a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3817657dbb9f</guid>
            <category><![CDATA[r-language]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[ecology]]></category>
            <dc:creator><![CDATA[Yps Henu]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 11:13:36 GMT</pubDate>
            <atom:updated>2026-08-10T11:13:36.383Z</atom:updated>
            <content:encoded><![CDATA[<p><em>*A practical walkthrough of alpha diversity in R with vegan — turn a raw abundance matrix into the four classic indices and modern Hill numbers, with code you can run today.*</em></p><p><strong>Two communities, same species count</strong></p><p>Suppose you just opened a spreadsheet from a vegetation survey. Twenty-four sample plots, forty species, and a column saying which elevation belt each plot belongs to: Low, Mid, or High. Now comes the question every community ecologist meets sooner or later — how do you reduce each plot to a small set of numbers that honestly describes how diverse it is?</p><p>The catch is that “diverse” can mean different things. Imagine two plots that both contain 30 species. In the first, abundance is spread evenly and every species is roughly equally common. In the second, a single species accounts for 90% of all individuals and the rest are rare. Both plots have a species richness of 30, but nobody would call them equally diverse. That is why alpha diversity is a <em>*family*</em> of indices rather than a single number. Each index weighs the two ingredients of diversity — how many species there are, and how evenly individuals are spread among them — a little differently.</p><p>Alpha diversity (α diversity) measures the diversity <strong>**within a single sample plot**</strong>, and it is the workhorse metric of community ecology. High diversity is frequently associated with community stability, resistance to invasion, and ecosystem functioning — but only if we can turn the fuzzy concept of “diversity” into something calculable and comparable across sites.</p><p>In this tutorial we will compute the four classic indices — <strong>**species richness (S), the Shannon index, the Simpson index, and Pielou’s evenness**</strong> — and then move on to the modern <strong>**Hill numbers**</strong> framework, which unifies them as <em>*effective numbers of species*</em>. Along the way we will hit the classic pitfalls: grouping columns hiding inside the abundance matrix, `vegan`’s counter-intuitive `simpson` return value, and the `0⁰ = 1` trap in R.</p><p><strong>1. The data: a simulated community along an elevation gradient</strong></p><p>To keep everything reproducible and self-contained, this tutorial uses a <strong>**simulated**</strong> community dataset. It mimics a plant community along an elevation gradient: <strong>**Low**</strong>, <strong>**Mid**</strong>, and <strong>**High**</strong>, with <strong>**8 sample plots per gradient**</strong> — 24 plots and 40 species in total. The generator builds in a clear ecological gradient on purpose: low-elevation plots are richer and more even, while high-elevation plots have fewer species and a stronger dominant species. That makes the results easy to check against expectations, which is exactly what you want when you are learning the method. The data is not tied to any real survey and exists purely for teaching.</p><p>The structure is simple:</p><p>| Column | Meaning | Example |</p><p>| — -| — -| — -|</p><p>| `Sample` | Plot identifier | Low01 |</p><p>| `Elevation` | Elevation group | Low / Mid / High |</p><p>| `Sp01`–`Sp40` | Abundance of each species (counts per plot) | 16.0, 32.6, 0, … |</p><p>Reading the file looks straightforward, but there is one detail you cannot skip: the abundance matrix has grouping columns mixed in, and those must be removed before any computation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*CuFev8n-vY3hJwQ-eFX6Bw.png" /></figure><p>```r</p><p><em># Read data</em></p><p><em>dat &lt;- </em><strong><em>read.csv</em></strong><em>(“sim_abundance.csv”)</em></p><p><em>elevation &lt;- dat$Elevation # grouping variable: elevation gradient</em></p><p><em>comm &lt;- dat[, -(1:2)] # abundance matrix (drop ID and grouping columns)</em></p><p><strong><em>rownames</em></strong><em>(comm) &lt;- dat$Sample</em></p><p><strong><em>dim</em></strong><em>(comm) # 24 plots × 40 species</em></p><p>```</p><p><em>```text</em></p><p><em>[1] 24 40</em></p><p>```</p><p>A lot of abundance tables carry a few columns of group information in front — plot ID, treatment, elevation, and so on. If you run `read.csv(…, row.names = 1)` naively, those grouping columns get pulled into the abundance matrix, and every index downstream will be silently wrong. This is probably the most common mistake in real workflows. The correct habit is to strip the ID and grouping columns first and keep only the species abundance block.</p><p>Before we compute anything, run a quick quality check:</p><p>```r</p><p><em># Data quality check</em></p><p><strong><em>stopifnot</em></strong><em>(</em><strong><em>all</em></strong><em>(!</em><strong><em>is.na</em></strong><em>(comm))) # no missing values</em></p><p><strong><em>stopifnot</em></strong><em>(</em><strong><em>all</em></strong><em>(</em><strong><em>rowSums</em></strong><em>(comm) &gt; 0)) # no empty plots</em></p><p><strong><em>summary</em></strong><em>(</em><strong><em>rowSums</em></strong><em>(comm)) # total abundance per plot</em></p><p>```</p><p>```text</p><p><em>Min. 1st Qu. Median Mean 3rd Qu. Max.</em></p><p><em>334.0 462.0 537.0 535.8 592.1 772.0</em></p><p>```</p><p>Total abundance across the 24 plots ranges from 334 to 772, and every plot has at least one species recorded. The data is safe to use.</p><p><strong>2. The four classic indices</strong></p><p><strong>2.1 Species richness (S)</strong></p><p>```r</p><p><strong><em>library</em></strong><em>(vegan)</em></p><p><em>S &lt;- specnumber(comm) # number of species per plot</em></p><p><strong><em>head</em></strong><em>(S)</em></p><p>```</p><p>```text</p><p><em>Low01 Low02 Low03 Low04 Low05 Low06</em></p><p><em>30 29 32 36 25 31</em></p><p>```</p><p>`specnumber()` counts, for each plot, how many species have abundance greater than zero. It is the most intuitive index you can compute — but it only counts species and ignores how abundance is distributed, so it carries limited information on its own. You almost always pair it with an evenness-type index.</p><p><strong>2.2 The Shannon index</strong></p><p>```r</p><p><em>Shannon &lt;- diversity(comm, index = “shannon”)</em></p><p><strong><em>head</em></strong><em>(Shannon)</em></p><p>```</p><p>```text</p><p><em>Low01 Low02 Low03 Low04 Low05 Low06</em></p><p><em>3.281841 3.154341 3.306462 3.400290 3.103742 3.299872</em></p><p>```</p><p>The Shannon index is defined as</p><p>$$H’ = -\<strong>sum_</strong>{i} p_i \cdot \ln(p_i)$$</p><p>where pᵢ is the relative abundance of species i. It weighs <strong>**both the number of species and their evenness**</strong>, and it ranges from 0 to ln(S). Seen through the lens of information theory, H′ is a measure of the “entropy” of the community: the more species there are and the more evenly they are distributed, the larger the entropy.</p><p><strong>2.3 The Simpson index (and the trap that trips everyone up)</strong></p><p>```r</p><p><em>Simpson &lt;- diversity(comm, index = “simpson”)</em></p><p><strong><em>head</em></strong><em>(Simpson)</em></p><p>```</p><p>```text</p><p><em>Low01 Low02 Low03 Low04 Low05 Low06</em></p><p><em>0.9585511 0.9509137 0.9589752 0.9624269 0.9507381 0.9584101</em></p><p>```</p><p>Here is the <strong>**easiest mistake in this whole tutorial**</strong>: `vegan`’s `diversity(index = “simpson”)` returns <strong>**1 − Σpᵢ²**</strong>, the <em>*Gini-Simpson*</em> diversity index — <strong>**not**</strong> Σpᵢ² itself. Σpᵢ² is the probability that two individuals drawn at random belong to the same species (the concentration D); the larger it is, the more dominance. The complement 1 − Σpᵢ² is the probability that two random individuals belong to different species; the larger <em>*that*</em> is, the more diverse. In this dataset the mean Simpson value per elevation group is High ≈ 0.879, Mid ≈ 0.940, and Low ≈ 0.955 — meaning that if you draw two plants at random, they will very likely belong to different species, and community differentiation is strong.</p><p>### <strong>2.4 Pielou’s evenness</strong></p><p>```r</p><p><em>Pielou &lt;- Shannon / </em><strong><em>log</em></strong><em>(S) # J’ = H’ / ln(S)</em></p><p><em>Pielou[S == 1] &lt;- 1 # when S=1, log(S)=0; set evenness to 1</em></p><p><strong><em>head</em></strong><em>(Pielou)</em></p><p>```</p><p>```text</p><p><em>Low01 Low02 Low03 Low04 Low05 Low06</em></p><p><em>0.9649074 0.9367580 0.9540432 0.9488689 0.9642317 0.9609449</em></p><p>```</p><p>Pielou’s evenness J′ is the ratio of the observed Shannon value to its theoretical maximum ln(S):</p><p>$$J’ = \<strong>frac</strong>{H’}{\ln(S)}$$</p><p>It ranges from 0 to 1 and isolates the evenness component by removing the effect of species number. The closer J′ is to 1, the more similar the species abundances are. Watch the edge case: when S = 1, ln(S) = 0 and you would be dividing by zero, so we replace those entries with 1 first.</p><p><strong>Combining and exporting the indices</strong></p><p>```r</p><p><em>alpha.index &lt;- </em><strong><em>data.frame</em></strong><em>(Sample = </em><strong><em>rownames</em></strong><em>(comm), Elevation = elevation,</em></p><p><em>Richness = S, Shannon = Shannon,</em></p><p><em>Simpson = Simpson, Pielou = Pielou)</em></p><p><strong><em>write.csv</em></strong><em>(alpha.index, “alpha_diversity_indices.csv”, row.names = FALSE)</em></p><p><strong><em>head</em></strong><em>(alpha.index, 3)</em></p><p>```</p><p>```text</p><p><em>Sample Elevation Richness Shannon Simpson Pielou</em></p><p><em>Low01 Low01 Low 30 3.281841 0.9585511 0.9649074</em></p><p><em>Low02 Low02 Low 29 3.154341 0.9509137 0.9367580</em></p><p><em>Low03 Low03 Low 32 3.306462 0.9589752 0.9540432</em></p><p>```</p><p><strong>Visualizing the four indices as boxplots</strong></p><p>Each index gets its own boxplot grouped by elevation, and `plot_grid` stitches them into a 2×2 panel. We use `ggpubr::ggboxplot` with the raw points jittered on top, and annotate all three pairwise comparisons with significance from a <strong>**Dunn post-hoc test with FDR (Benjamini–Hochberg) correction**</strong> — significant pairs get asterisks, non-significant pairs get `ns`.</p><p>Why not pairwise t-tests or a plain ANOVA? Three groups mean three pairwise comparisons that need a multiple-testing correction, and two of our indices (Simpson, Pielou) violate variance homogeneity (Levene p &lt; 0.05), so the parametric assumptions do not hold. We therefore run an overall Kruskal–Wallis test first (significant for all four indices, p &lt; 0.001) and then the non-parametric Dunn test with FDR correction for the pairwise comparisons — a standard, defensible choice for diversity data.</p><p>```r</p><p><strong><em>library</em></strong><em>(ggpubr)</em></p><p><strong><em>library</em></strong><em>(cowplot)</em></p><p><strong><em>library</em></strong><em>(rstatix)</em></p><p><em>alpha.index$Elevation &lt;- </em><strong><em>factor</em></strong><em>(alpha.index$Elevation, levels = </em><strong><em>c</em></strong><em>(“Low”, “Mid”, “High”))</em></p><p><strong><em>plot_index</em></strong><em> &lt;- function(yvar, ylabname) {</em></p><p><em>d &lt;- </em><strong><em>data.frame</em></strong><em>(Elevation = alpha.index$Elevation, value = alpha.index[[yvar]])</em></p><p><em># Dunn post-hoc + FDR(BH) correction, keep all three pairs (ns shown)</em></p><p><em>dunn &lt;- rstatix::dunn_test(d, value ~ Elevation, p.adjust.method = “BH”)</em></p><p><em>ymax &lt;- </em><strong><em>max</em></strong><em>(d$value)</em></p><p><em>step &lt;- </em><strong><em>diff</em></strong><em>(</em><strong><em>range</em></strong><em>(d$value)) * 0.05</em></p><p><em>dunn$y.position &lt;- ymax + step * </em><strong><em>seq_len</em></strong><em>(</em><strong><em>nrow</em></strong><em>(dunn))</em></p><p><em>ggboxplot(d, x = “Elevation”, y = “value”,</em></p><p><em>color = “Elevation”,</em></p><p><em>palette = </em><strong><em>c</em></strong><em>(“#4DBBD5”, “#E6A817”, “#E64B35”),</em></p><p><em>xlab = “Elevation”, ylab = ylabname,</em></p><p><em>add = “jitter”, add.params = list(size = 1)) +</em></p><p><em>stat_pvalue_manual(dunn, label = “p.adj.signif”, tip.length = 0.01) +</em></p><p><em>scale_y_continuous(expand = expansion(mult = </em><strong><em>c</em></strong><em>(0.05, 0.15))) +</em></p><p><em>theme(legend.position = “none”,</em></p><p><em>axis.ticks.length = unit(-0.1, “cm”))</em></p><p><em>}</em></p><p><em>p1 &lt;- plot_index(“Richness”, “Richness”)</em></p><p><em>p2 &lt;- plot_index(“Shannon”, “Shannon”)</em></p><p><em>p3 &lt;- plot_index(“Simpson”, “Simpson”)</em></p><p><em>p4 &lt;- plot_index(“Pielou”, “Pielou”)</em></p><p><em>plot_grid(p1, p2, p3, p4, ncol = 2,</em></p><p><em>labels = </em><strong><em>c</em></strong><em>(“a”, “b”, “c”, “d”), label_x = 0)</em></p><p>```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kPQgHFkSnCWZPNBsdvdKQ.png" /></figure><p>Wrapping the plotting code in a function `plot_index()` is the cleanest way to avoid writing the `ggboxplot` call four times — it is the standard pattern for batch-generating figures.</p><p><strong>3. Going further: inverse Simpson and Hill numbers</strong></p><p><strong>3.1 Inverse Simpson — the effective number of species</strong></p><p>```r</p><p><em>invSimpson &lt;- diversity(comm, index = “invsimpson”)</em></p><p><strong><em>head</em></strong><em>(invSimpson)</em></p><p>```</p><p>```text</p><p><em>Low01 Low02 Low03 Low04 Low05 Low06</em></p><p><em>24.12607 20.37228 24.37550 26.61482 20.29967 24.04427</em></p><p>```</p><p>Inverse Simpson is 1/Σpᵢ², and it has a wonderfully concrete interpretation: it tells you <strong>**how many equally abundant species the community is effectively equivalent to**</strong>. If ten species had perfectly equal abundances, inverse Simpson would be 10; if one species made up 90% of the individuals, it would drop toward 1. That is why it is so much easier to explain than the raw Simpson value — it gives you an <em>*effective number of species*</em>.</p><p>At this point we have used all three common `index` arguments of `diversity()`. Here is the cheat sheet:</p><p>| index argument | Returns | Range | Meaning |</p><p>| — -| — -| — -| — -|</p><p>| `”shannon”` | H′ = −Σpᵢ·ln(pᵢ) | [0, ln S] | Shannon diversity index |</p><p>| `”simpson”` | 1 − Σpᵢ² | [0, 1] | Gini-Simpson diversity index |</p><p>| `”invsimpson”` | 1/Σpᵢ² | ≥ 1 | Inverse Simpson (effective number of species) |</p><p><strong>3.2 Hill numbers: one framework for all of them</strong></p><p>Hill numbers use a single order parameter q to put different diversity indices into one framework:</p><p>```r</p><p><em>hill &lt;- </em><strong><em>data.frame</em></strong><em>(q0 = S, q1 = </em><strong><em>exp</em></strong><em>(Shannon), q2 = invSimpson)</em></p><p><strong><em>head</em></strong><em>(hill, 3)</em></p><p>```</p><p>```text</p><p><em>q0 q1 q2</em></p><p><em>Low01 30 26.62473 24.12607</em></p><p><em>Low02 29 23.43760 20.37228</em></p><p><em>Low03 32 27.28840 24.37550</em></p><p>```</p><p>The three orders we need:</p><p>| Order q | Formula | Corresponding index | Emphasis |</p><p>| — -| — -| — -| — -|</p><p>| q = 0 | S | Species richness | Weights rare species most |</p><p>| q = 1 | exp(H′) | Exponential Shannon | Balances richness and evenness |</p><p>| q = 2 | 1/Σpᵢ² | Inverse Simpson | Focuses on dominant species |</p><p>Notice that q0 ≥ q1 ≥ q2, and the bigger the drop as q increases, the more the community is dominated by a few abundant species. That is precisely the value of Hill numbers: within one framework you can watch the effective number of species change as you shift weight between rare species, common species, and dominant species.</p><p><strong>3.3 The Hill curve: q from 0 to 2</strong></p><p>```r</p><p><strong><em>library</em></strong><em>(dplyr)</em></p><p><strong><em>hill_num</em></strong><em> &lt;- function(x, q) {</em></p><p><em>p &lt;- x[x &gt; 0] / </em><strong><em>sum</em></strong><em>(x) # keep only present species</em></p><p><em>if (q == 0) return(</em><strong><em>length</em></strong><em>(p)) # q=0 is species richness</em></p><p><em>if (q == 1) return(</em><strong><em>exp</em></strong><em>(-</em><strong><em>sum</em></strong><em>(p * </em><strong><em>log</em></strong><em>(p))))</em></p><p><em>(</em><strong><em>sum</em></strong><em>(p^q))^(1 / (1 — q))</em></p><p><em>}</em></p><p><em>qs &lt;- </em><strong><em>seq</em></strong><em>(0, 2, by = 0.1)</em></p><p><em>hill_long &lt;- </em><strong><em>do.call</em></strong><em>(rbind, </em><strong><em>lapply</em></strong><em>(1:</em><strong><em>nrow</em></strong><em>(comm), function(i)</em></p><p><strong><em>data.frame</em></strong><em>(Sample = </em><strong><em>rownames</em></strong><em>(comm)[i], Elevation = elevation[i], q = qs,</em></p><p><em>hill = </em><strong><em>sapply</em></strong><em>(qs, function(q) hill_num(comm[i, ], q)))))</em></p><p><em>hill_summary &lt;- hill_long %&gt;%</em></p><p><em>group_by(Elevation, q) %&gt;%</em></p><p><em>summarise(mean_hill = </em><strong><em>mean</em></strong><em>(hill), .groups = “drop”)</em></p><p><em>ggplot() +</em></p><p><em>geom_line(data = hill_long, aes(q, hill, group = Sample, colour = Elevation),</em></p><p><em>linewidth = 0.3, alpha = 0.3) +</em></p><p><em>geom_line(data = hill_summary, aes(q, mean_hill, colour = Elevation),</em></p><p><em>linewidth = 0.9) +</em></p><p><em>scale_colour_manual(values = </em><strong><em>c</em></strong><em>(Low = “#4DBBD5”, Mid = “#E6A817”, High = “#E64B35”)) +</em></p><p><em>labs(x = “Order q”, y = “Effective number of species”)</em></p><p>```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDBWzy66gzDhoTJ4iWWM5g.png" /></figure><p>There is a subtle but critical detail in the `hill_num()` function: <strong>**only sum over species with p &gt; 0**</strong>. In R, `0⁰ = 1`, so if you simply divide by the total and compute `sum(p^q)`, at q = 0 every zero-abundance species is also counted as 1 — and every plot’s q0 becomes the total species pool instead of its real richness. That single bug makes all the Hill curves overlap exactly at q = 0 and hides the real differences between groups.</p><p><strong>4. Reading the results</strong></p><p>The boxplots tell a consistent story: no matter which classic index you pick, diversity declines with elevation. Richness means are Low ≈ 29.9 &gt; Mid ≈ 23.6 &gt; High ≈ 16.4; Shannon drops from 3.23 (Low) to 2.38 (High); Pielou falls from 0.95 to 0.85. In other words, low-elevation communities hold more species and spread abundance more evenly, while high-elevation communities are species-poor and more strongly dominated. The four indices show a remarkably coherent gradient: an overall Kruskal–Wallis test is significant for every index (all p &lt; 0.001), and after the Dunn post-hoc with FDR correction the Low–High and Mid–High comparisons are significant, while Low–Mid is not — so the main divide in this simulated gradient sits between the low and high elevation ends.</p><p>The Hill curves add a layer of nuance about evenness. The high-elevation group has the steepest drop between q = 0 and q = 1 — effective species go from about 16 down to about 10 — which says its diversity is carried mostly by a handful of dominant species. The low-elevation curve is flatter and stays high even when weight is placed on rare species (small q). That shape — “the higher q, the stronger the relative advantage of low elevation” — is exactly why Hill numbers beat any single index: one figure shows species number (q = 0), common species (q = 1), and dominant species (q = 2) at the same time, instead of three separate plots.</p><p>In real field studies, remember that the relationship between elevation and diversity is not a law. Whether diversity rises or falls with elevation depends on sampling design, environmental covariates, and the specific system you study, and it should be judged with proper hypothesis testing. The takeaway from this tutorial is the <em>*workflow*</em>.</p><p><strong>5. The complete script</strong></p><p>Here is everything from this tutorial in one runnable script. To run it with your own data, make sure the abundance matrix has the same shape: one row per plot, one column per species, plot names as row names or a dedicated column, and any grouping variables (treatment, elevation, habitat) stored separately for grouped visualization.</p><p>```r</p><p><em># ============================================================</em></p><p><em># Alpha diversity indices: Richness / Shannon / Simpson / Pielou / Hill numbers</em></p><p><em># Data: sim_abundance.csv (24 plots × 40 species, elevation gradient)</em></p><p><em># ============================================================</em></p><p><strong><em>library</em></strong><em>(vegan)</em></p><p><strong><em>library</em></strong><em>(dplyr)</em></p><p><em># — — — — — 1. Read data — — — — —</em></p><p><em>dat &lt;- </em><strong><em>read.csv</em></strong><em>(“sim_abundance.csv”, header = TRUE)</em></p><p><em>elevation &lt;- dat$Elevation</em></p><p><em>comm &lt;- dat[, -(1:2)]</em></p><p><strong><em>rownames</em></strong><em>(comm) &lt;- dat$Sample</em></p><p><strong><em>dim</em></strong><em>(comm)</em></p><p><em># — — — — — 2. Data quality check — — — — —</em></p><p><strong><em>stopifnot</em></strong><em>(</em><strong><em>all</em></strong><em>(!</em><strong><em>is.na</em></strong><em>(comm)))</em></p><p><strong><em>stopifnot</em></strong><em>(</em><strong><em>all</em></strong><em>(</em><strong><em>rowSums</em></strong><em>(comm) &gt; 0))</em></p><p><strong><em>summary</em></strong><em>(</em><strong><em>rowSums</em></strong><em>(comm))</em></p><p><em># — — — — — 3. Species richness (S) — — — — —</em></p><p><em>S &lt;- specnumber(comm)</em></p><p><em># — — — — — 4. Shannon index — — — — —</em></p><p><em>Shannon &lt;- diversity(comm, index = “shannon”)</em></p><p><em># — — — — — 5. Simpson index (Gini-Simpson) — — — — —</em></p><p><em>Simpson &lt;- diversity(comm, index = “simpson”)</em></p><p><em># — — — — — 6. Pielou evenness — — — — —</em></p><p><em>Pielou &lt;- Shannon / </em><strong><em>log</em></strong><em>(S)</em></p><p><em>Pielou[S == 1] &lt;- 1</em></p><p><em># — — — — — 7. Inverse Simpson — — — — —</em></p><p><em>invSimpson &lt;- diversity(comm, index = “invsimpson”)</em></p><p><em># — — — — — 8. Hill numbers — — — — —</em></p><p><em>hill &lt;- </em><strong><em>data.frame</em></strong><em>(q0 = S, q1 = </em><strong><em>exp</em></strong><em>(Shannon), q2 = invSimpson)</em></p><p><em># — — — — — 9. Merge and export — — — — —</em></p><p><em>alpha.index &lt;- </em><strong><em>data.frame</em></strong><em>(Sample = </em><strong><em>rownames</em></strong><em>(comm), Elevation = elevation,</em></p><p><em>Richness = S, Shannon = Shannon,</em></p><p><em>Simpson = Simpson, Pielou = Pielou,</em></p><p><em>invSimpson = invSimpson,</em></p><p><em>Hill_q0 = hill$q0, Hill_q1 = hill$q1, Hill_q2 = hill$q2)</em></p><p><strong><em>write.csv</em></strong><em>(alpha.index, “alpha_diversity_indices.csv”, row.names = FALSE)</em></p><p><em># — — — — — 10. Summary by elevation group — — — — —</em></p><p><em>group_summary &lt;- alpha.index %&gt;%</em></p><p><em>group_by(Elevation) %&gt;%</em></p><p><em>summarise(across(</em><strong><em>c</em></strong><em>(Richness, Shannon, Simpson, Pielou, invSimpson),</em></p><p><em>list(mean = ~</em><strong><em>round</em></strong><em>(</em><strong><em>mean</em></strong><em>(.x), 3))))</em></p><p><strong><em>print</em></strong><em>(</em><strong><em>as.data.frame</em></strong><em>(group_summary))</em></p><p>```</p><p><strong>6. Key takeaways</strong></p><p>1. <strong>**Strip the grouping columns.**</strong> If plot IDs, treatments, or elevation live inside the abundance table, remove them before computing — otherwise every index is silently wrong.</p><p>2. <strong>**Pick the right </strong>`index`<strong> argument.**</strong> `vegan::diversity()` has three common settings: `shannon`, `simpson` (returns 1 − Σp²), and `invsimpson` (returns 1/Σp²).</p><p>3. <strong>**Check the data first.**</strong> Look for missing values (`is.na`) and empty plots (`rowSums &gt; 0`); empty plots will crash or distort diversity and distance calculations.</p><p>4. <strong>**Handle the edge cases.**</strong> Pielou divides by ln(S) and fails at S = 1; the Hill function must filter to p &gt; 0 species to avoid the ⁰⁰ = 1 trap.</p><p>5. <strong>**Report indices as a set.**</strong> Richness and evenness are complementary dimensions; one index alone tells an incomplete story.</p><p>6. <strong>**Visualize over tabulate.**</strong> A boxplot with overlaid points reveals the real distribution and outliers that a single mean hides.</p><p>7. <strong>**Hill numbers for the modern workflow.**</strong> One curve across q = 0–2 conveys richness, evenness, and dominance in a single figure.</p><p><strong>Wrap up</strong></p><p>Alpha diversity is a family of questions — how many species, how even — and R’s `vegan` package answers them in a few lines. Start with the four classic indices, keep the “`simpson` returns Gini-Simpson” detail in mind, and reach for Hill numbers when you want a single figure that shows the whole picture.</p><p>If this walkthrough helped you, give it a clap 👏 (you can clap up to 50 times), leave a comment if any step tripped you up, and follow for more R tutorials on ecological data analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3817657dbb9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ANOVA in R: Single-Factor and Two-Way Analysis of Variance from Scratch]]></title>
            <link>https://medium.com/@yps.henu/anova-in-r-single-factor-and-two-way-analysis-of-variance-from-scratch-d8ef7a126660?source=rss-cb36c3a909a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8ef7a126660</guid>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[r-language]]></category>
            <category><![CDATA[ecology]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Yps Henu]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 13:32:14 GMT</pubDate>
            <atom:updated>2026-08-08T13:36:51.167Z</atom:updated>
            <content:encoded><![CDATA[<p>## A complete workflow from assumption checks to interaction effects and emmeans simple effects for ecologists</p><p>— -</p><p>“Does plant diversity differ between my fertilized and control plots?” “Do different ecosystems respond to nitrogen addition the same way?” If you work with ecological data, you ask questions like these almost daily. When you have more than two groups to compare, running pairwise t-tests one by one is not only tedious — it quietly inflates your chance of a false positive. Each test you add makes it more likely that at least one “significant” result is just luck.</p><p>What you need is **analysis of variance (ANOVA)**.</p><p>ANOVA uses a single **F-test** to answer “are all group means equal?” in one go, and once that test is significant you can dig deeper with a *post-hoc* multiple-comparison procedure to find exactly which groups differ. In this tutorial we’ll walk through the whole workflow a paper would actually use, from checking the assumptions, through a single-factor ANOVA, all the way to a two-way ANOVA with an interaction effect — and then we’ll look at how to decompose a significant interaction with `emmeans`.</p><p>Our running example: **how nitrogen addition level and ecosystem type affect plant diversity** (measured with the Shannon index).</p><p>— -</p><p>## How ANOVA works: splitting up the variance</p><p>A **single-factor ANOVA** tests the effect of one categorical factor (like nitrogen level) on one continuous response (like the Shannon diversity index). The core idea is to split the total variability in your data into two parts:</p><p>- **Between-group variation**: how far each group mean sits from the overall mean — this reflects the *treatment effect*.</p><p>- **Within-group variation**: how much the individual observations inside each group differ from each other — this reflects *random error*.</p><p>The F-statistic is simply **between-group mean square / within-group mean square**. If the treatment effect is much larger than the random noise, F gets big, the p-value drops below 0.05, and you reject the null hypothesis that all group means are equal — meaning at least one group really does differ from the others.</p><p>A **two-way ANOVA** considers two factors at once (nitrogen level × ecosystem) and lets you test their **interaction** — whether the effect of one factor depends on the level of the other. For example, nitrogen addition might suppress diversity much more strongly in grasslands than in croplands. That difference in response is exactly what we call an interaction.</p><p>**ANOVA rests on three assumptions** (and this matters — if they’re violated, your results can’t be trusted):</p><p>| Assumption | How to check | Requirement |</p><p>| — — — | — — — — -| — — — |</p><p>| Independence | Guaranteed by experimental design | Each observation is independent |</p><p>| Normality | Shapiro-Wilk test (**on the residuals**) | p &gt; 0.05 (no evidence against normality) |</p><p>| Homogeneity of variance | Levene test | p &gt; 0.05 (no evidence against equal variances) |</p><p>One subtle point: these assumption tests have the null hypothesis *that the assumption holds* (residuals normal / variances equal). So a p-value **above** 0.05 is the good outcome — no evidence to reject. If p drops below 0.05, the assumption is violated and you need to switch approaches. And here the fix depends on your design: for a single-factor design with unequal variances, prefer **Welch ANOVA** (`oneway.test()`); for a two-factor design you can’t simply fall back on Kruskal-Wallis (that’s a rank-based non-parametric test, not an “ANOVA substitute for unequal variances”). Instead, choose a robust ANOVA, a permutation test, or a generalized / mixed-effects model suited to your study design.</p><p>— -</p><p>## Getting the data ready</p><p>We’ll use a simulated ecological dataset that mimics a “nitrogen level × ecosystem” two-factor experiment on plant Shannon diversity.</p><p>**Experimental design (3 × 3 = 9 groups, 20 quadrats each, 180 rows):**</p><p>| Factor | Levels |</p><p>| — — — | — — — |</p><p>| Nlevel (nitrogen addition) | Control / Low_N / High_N |</p><p>| Ecosystem | Grassland / Forest / Cropland |</p><ul><li>*Response variable:** the Shannon diversity index (continuous), with Simpson, Pielou, and species count S available as backups.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0y_Ki7dXL63koHsBj5s70g.png" /></figure><p>```r</p><p><em># Load the data</em></p><p><em>dat &lt;- read.csv(“anova_diversity.csv”, header = TRUE)</em></p><p><em>dat$Ecosystem &lt;- factor(dat$Ecosystem)</em></p><p><em>dat$Nlevel &lt;- factor(dat$Nlevel, levels = c(“Control”, “Low_N”, “High_N”))</em></p><p><em>head(dat)</em></p><p>```</p><p>The data file `anova_diversity.csv` is provided with the article — just copy the code and run it. (If you’re following along with your own data, the final section shows you how to swap in your own file.)</p><p>A quick note on the biology we built into the simulation: nitrogen addition *reduces* plant diversity, and we deliberately set **grasslands as the most sensitive** to nitrogen — that choice is the seed of the interaction effect you’ll see later. It’s also ecologically grounded: nitrogen deposition suppresses plant diversity by raising soil nitrogen availability, which favors a few nitrogen-efficient competitive dominants and crowds out species adapted to low-nutrient habitats, so community diversity falls (Bobbink et al., 2010, *Global Change Biology*; Stevens et al., 2004, *Science*). Grassland species assemblages are especially sensitive to nutrient shifts and turn over quickly, so they’re generally expected to respond more strongly to nitrogen than forests or croplands.</p><p>— -</p><p>## Step 1: Check the assumptions</p><p>### Normality — on the residuals, not the raw data</p><p>A very common beginner mistake is running Shapiro-Wilk on the *raw observations*. But the normality assumption of ANOVA applies to the **model residuals**, not to the data you measured. Even if the observations within each group aren’t themselves normally distributed, as long as the residuals look roughly normal, the parametric test is still valid:</p><p>```r</p><p><em>library(car)</em></p><p><em># Fit the single-factor model first, then check its residuals</em></p><p><em>fit1 &lt;- aov(Shannon ~ Nlevel, data = dat)</em></p><p><em>shapiro.test(residuals(fit1))</em></p><p>```</p><p>Example output:</p><p>```</p><p><em>Shapiro-Wilk normality test</em></p><p><em>W = 0.99373, p-value = 0.6408</em></p><p>```</p><p>p = 0.641 &gt; 0.05: no evidence to reject residual normality, so the residuals look approximately normal (and you can combine this with the Q-Q plot below for a more complete judgment).</p><p>### Homogeneity of variance — the Levene test</p><p>We also need the group variances to be roughly similar. The recommended tool is the **Levene test** from the `car` package. `car::leveneTest()` centers on the median by default, which makes it a **Brown-Forsythe type** test — generally more robust to non-normal data than the classic Bartlett test:</p><p>```r</p><p><em>leveneTest(Shannon ~ Nlevel, data = dat)</em></p><p>```</p><p>Example output:</p><p>```</p><p><em>Df F value Pr(&gt;F)</em></p><p><em>group 2 1.9516 0.1451</em></p><p><em>177</em></p><p>```</p><p>p = 0.145 &gt; 0.05: no evidence against equal variances, so we can treat the group variances as similar.</p><p>### Visualizing normality with a Q-Q plot</p><p>The Q-Q plot is a great complement to the formal test. Here the points hug the diagonal fairly closely, with only slight deviation at the tails — visual support for the conclusion that the residuals are approximately normal.</p><p>```r</p><p><em>library(ggplot2)</em></p><p><em>p_qq &lt;- ggplot(data.frame(res = residuals(fit1)), aes(sample = res)) +</em></p><p><em>stat_qq(color = “#5B8CC9”, alpha = 0.7) +</em></p><p><em>stat_qq_line(color = “#1F3B73”, linewidth = 0.5) +</em></p><p><em>labs(title = “Q-Q plot of ANOVA residuals”, x = “Theoretical quantiles”,</em></p><p><em>y = “Sample quantiles”) +</em></p><p><em>theme_classic(base_size = 8, base_family = “Arial”) +</em></p><p><em>theme(axis.line = element_line(linewidth = 0.4),</em></p><p><em>axis.ticks = element_line(linewidth = 0.4),</em></p><p><em>panel.grid = element_blank())</em></p><p>```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUzHei9hwN_pb8s-h_9sKA.png" /></figure><p>— -</p><p>## Step 2: Single-factor ANOVA — the effect of nitrogen level</p><p>With the assumptions satisfied, fit the single-factor model with `aov()` and view the F-test with `summary()`:</p><p>```r</p><p><em>summary(fit1)</em></p><p>```</p><p>Example output:</p><p>```</p><p><em>Df Sum Sq Mean Sq F value Pr(&gt;F)</em></p><p><em>Nlevel 2 26.860 13.430 125.2 &lt; 2.2e-16 ***</em></p><p><em>Residuals 177 18.997 0.107</em></p><p>```</p><p>F(2, 177) = 125.2, p &lt; 0.001: nitrogen level significantly affects Shannon diversity. But “significant overall” does *not* mean “every pair of groups differs.” That’s where a **post-hoc multiple-comparison** comes in — to locate the specific differences.</p><p>**Why not just run pairwise t-tests?** With three groups, pairwise comparisons mean 3 t-tests. Judging each at α = 0.05, the family-wise error rate balloons to roughly 1 − (1 − 0.05)³ ≈ 14% — far above the nominal level. **Tukey HSD (Honestly Significant Difference)** corrects for this inflation using the *studentized range distribution*, holding the family-wise error rate at α. Compared with a Bonferroni correction (which divides α by the number of comparisons — conservative but low in power), Tukey is the more efficient standard choice when you want to compare *all* pairs. Only when your goal is “compare every treatment against a control” (rather than pairwise) should you reach for the **Dunnett test** instead.</p><p>```r</p><p><em>TukeyHSD(fit1)</em></p><p>```</p><p>Example output:</p><p>```</p><p><em>$Nlevel</em></p><p><em>diff lwr upr p adj</em></p><p><em>Low_N-Control -0.5491233 -0.690464 -0.407783 0.000000</em></p><p><em>High_N-Control -0.9419133 -1.083254 -0.800573 0.000000</em></p><p><em>High_N-Low_N -0.3927900 -0.534130 -0.251450 0.000000</em></p><p>```</p><p>All three pairwise comparisons are significant (p adj all &lt; 0.001). **diff** is the mean difference and **lwr/upr** are the 95% confidence limits. The pattern is clear: nitrogen addition significantly lowers diversity — High_N sits about 0.94 below Control, Low_N about 0.55 below.</p><p>The boxplot tells the same story visually: three boxes in a blue gradient (light → dark as nitrogen increases), with Tukey letters a/b/c labeled above each box — different letters mean the groups differ significantly. Reading left to right, the medians step down (roughly 2.86 → 2.23 → 1.89), matching the statistics (means of 2.81, 2.26, 1.87) and showing the suppressive effect of nitrogen on diversity at a glance.</p><p>```r</p><p><em>library(multcompView) # Tukey letter computation</em></p><p><em># Compute the Tukey letters (a/b/c)</em></p><p><em>tk &lt;- TukeyHSD(fit1)$Nlevel</em></p><p><em>lv &lt;- levels(dat$Nlevel)</em></p><p><em>pmat &lt;- matrix(1, 3, 3, dimnames = list(lv, lv))</em></p><p><em>for (pr in rownames(tk)) {</em></p><p><em># Note: splitting group names on “-” assumes your level names contain no hyphen;</em></p><p><em># if they do (e.g., “Low-N”), switch to a more robust interface like multcompLetters4()</em></p><p><em>v &lt;- strsplit(pr, “-”)[[1]]</em></p><p><em>pmat[v[2], v[1]] &lt;- pmat[v[1], v[2]] &lt;- tk[pr, “p adj”]</em></p><p><em>}</em></p><p><em>let1 &lt;- multcompLetters(pmat)$Letters</em></p><p><em>lab1 &lt;- data.frame(Nlevel = names(let1), letters = let1,</em></p><p><em>y = tapply(dat$Shannon, dat$Nlevel, max) + 0.1)</em></p><p><em>p_oneway &lt;- ggplot(dat, aes(x = Nlevel, y = Shannon, fill = Nlevel)) +</em></p><p><em>geom_boxplot(alpha = 0.85, outlier.shape = NA, linewidth = 0.4) +</em></p><p><em>geom_jitter(width = 0.12, size = 0.6, alpha = 0.35, color = “grey35”) +</em></p><p><em>geom_text(data = lab1, aes(x = Nlevel, y = y, label = letters),</em></p><p><em>size = 3, fontface = “bold”) +</em></p><p><em>scale_fill_manual(values = c(Control = “#D6E4F0”, Low_N = “#5B8CC9”,</em></p><p><em>High_N = “#1F3B73”)) +</em></p><p><em>labs(x = “Nitrogen addition level”, y = “Shannon diversity index”) +</em></p><p><em>theme_classic(base_size = 8, base_family = “Arial”) +</em></p><p><em>theme(legend.position = “none”,</em></p><p><em>axis.line = element_line(linewidth = 0.4),</em></p><p><em>axis.ticks = element_line(linewidth = 0.4),</em></p><p><em>panel.grid = element_blank())</em></p><p>```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8df5K7ukTVhc6D0kxvARQ.png" /></figure><p>— -</p><p>## Step 3: Two-way ANOVA — nitrogen × ecosystem</p><p>Now we consider both factors together. We’ll start with the **main-effects model** (additive, no interaction):</p><p>```r</p><p><em># Main-effects model: only the individual effects of the two factors</em></p><p><em>fit2a &lt;- aov(Shannon ~ Nlevel + Ecosystem, data = dat)</em></p><p><em>summary(fit2a)</em></p><p>```</p><p>Example output:</p><p>```</p><p><em>Df F value Pr(&gt;F)</em></p><p><em>Nlevel 2 154.465 &lt; 2.2e-16 ***</em></p><p><em>Ecosystem 2 21.693 3.83e-09 ***</em></p><p><em>Residuals 175</em></p><p>```</p><p>Both factors are highly significant. Next we fit the **interaction model** to ask whether nitrogen’s effect changes across ecosystems:</p><p>```r</p><p><em># Interaction model: allow nitrogen and ecosystem to interact</em></p><p><em>fit2b &lt;- aov(Shannon ~ Nlevel * Ecosystem, data = dat)</em></p><p><em>summary(fit2b)</em></p><p>```</p><p>Example output:</p><p>```</p><p><em>Df F value Pr(&gt;F)</em></p><p><em>Nlevel 2 164.3332 &lt; 2.2e-16 ***</em></p><p><em>Ecosystem 2 23.0791 1.34e-09 ***</em></p><p><em>Nlevel:Ecosystem 4 3.7951 0.005537 **</em></p><p><em>Residuals 171</em></p><p>```</p><p>**The interaction term Nlevel:Ecosystem is significant (F = 3.80, p = 0.0055)**, which tells us that nitrogen’s effect on diversity genuinely depends on the ecosystem type — different ecosystems respond to nitrogen with different intensities.</p><p>&gt; **Check the assumptions on the model you actually use.** In step 1 we tested the residuals of the single-factor model `fit1`, but the model we really want to interpret is the two-way interaction model `fit2b`. The right habit is to re-run the assumption checks (normality + homogeneity) on the residuals of the *final* model, rather than assuming the single-factor result carries over:</p><p>```r</p><p><em># Assumption checks on the final two-way model</em></p><p><em>shapiro.test(residuals(fit2b))</em></p><p><em>leveneTest(residuals(fit2b) ~ interaction(dat$Nlevel, dat$Ecosystem))</em></p><p>```</p><p>Example output:</p><p>```</p><p><em>Shapiro-Wilk normality test</em></p><p><em>W = 0.99601, p-value = 0.919</em></p><p><em>Levene’s Test for Homogeneity of Variance (center = median)</em></p><p><em>Df F value Pr(&gt;F)</em></p><p><em>group 8 0.6552 0.7302</em></p><p><em>171</em></p><p>```</p><p>The `fit2b` residuals give p = 0.919 for normality and p = 0.730 for homogeneity — the two-way model’s assumptions are satisfied too. **Whether you’re running a one-way or a two-way ANOVA, do residual diagnostics on the final model you interpret.** That’s the scientific habit — not “check once and forget.”</p><p>&gt; **Formula shorthand:** `A + B` is the main-effects model; `A * B` expands automatically to `A + B + A:B` (interaction included). When the interaction is significant, keep it in the model and interpret it. When it isn’t, resist the urge to delete it mechanically just because p is large — decide based on your study design, your pre-specified hypotheses, and model-simplification principles, simplifying to the additive model only when that’s justified.</p><p>Because the interaction is significant, you shouldn’t just compare Nlevel across all data pooled together — that would mash the three ecosystems into one blob and hide the interaction. Instead you run **simple effects** on the full model: fix Ecosystem, and compare the three Nlevel groups *within each panel*. The recommended approach for research is to use the `emmeans` package on the full model `fit2b`. It computes everything with a **single shared residual variance and degrees of freedom (df = 171)**, which is more rigorous and accurate than splitting the data into subsets and running a separate ANOVA on each piece:</p><p>```r</p><p><em>library(emmeans)</em></p><p><em># Simple effects on the full model (fix Ecosystem, compare Nlevel within panels)</em></p><p><em>emm &lt;- emmeans(fit2b, ~ Nlevel | Ecosystem)</em></p><p><em>pairs(emm, adjust = “tukey”) # pairwise Nlevel comparison within each Ecosystem</em></p><p><em># Compute per-panel letters from the emmeans adjusted p-values (shared df=171)</em></p><p><em>ct &lt;- as.data.frame(contrast(emm, method = “pairwise”, adjust = “tukey”))</em></p><p><em>emmeans_letters &lt;- function(ct_df, fac_levels) {</em></p><p><em>pmat &lt;- matrix(1, length(fac_levels), length(fac_levels),</em></p><p><em>dimnames = list(fac_levels, fac_levels))</em></p><p><em>for (i in seq_len(nrow(ct_df))) {</em></p><p><em>nm &lt;- strsplit(as.character(ct_df$contrast[i]), “ — “)[[1]]</em></p><p><em>pmat[nm[2], nm[1]] &lt;- pmat[nm[1], nm[2]] &lt;- ct_df$p.value[i]</em></p><p><em>}</em></p><p><em>multcompLetters(pmat)$Letters</em></p><p><em>}</em></p><p><em>let2 &lt;- lapply(levels(dat$Ecosystem), function(ec)</em></p><p><em>emmeans_letters(ct[ct$Ecosystem == ec, ], levels(dat$Nlevel)))</em></p><p><em>names(let2) &lt;- levels(dat$Ecosystem)</em></p><p><em>lab2 &lt;- do.call(rbind, lapply(names(let2), function(ec) {</em></p><p><em>data.frame(Ecosystem = ec, Nlevel = names(let2[[ec]]), letters = let2[[ec]],</em></p><p><em>y = tapply(dat$Shannon[dat$Ecosystem == ec],</em></p><p><em>dat$Nlevel[dat$Ecosystem == ec], max) + 0.12)</em></p><p><em>}))</em></p><p><em>p_twoway &lt;- ggplot(dat, aes(x = Nlevel, y = Shannon, fill = Nlevel)) +</em></p><p><em>geom_boxplot(alpha = 0.85, outlier.shape = NA, linewidth = 0.4) +</em></p><p><em>geom_jitter(width = 0.12, size = 0.6, alpha = 0.35, color = “grey35”) +</em></p><p><em>geom_text(data = lab2, aes(x = Nlevel, y = y, label = letters),</em></p><p><em>size = 3, fontface = “bold”) +</em></p><p><em>facet_wrap(~ Ecosystem, ncol = 3) +</em></p><p><em>scale_fill_manual(values = c(Control = “#D6E4F0”, Low_N = “#5B8CC9”,</em></p><p><em>High_N = “#1F3B73”)) +</em></p><p><em>labs(x = “Nitrogen addition level”, y = “Shannon diversity index”) +</em></p><p><em>theme_classic(base_size = 8, base_family = “Arial”) +</em></p><p><em>theme(legend.position = “none”,</em></p><p><em>strip.text = element_text(face = “bold”),</em></p><p><em>axis.line = element_line(linewidth = 0.4),</em></p><p><em>axis.ticks = element_line(linewidth = 0.4),</em></p><p><em>panel.grid = element_blank())</em></p><p>```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewq4rJFmxyzDibaXgk655A.png" /></figure><p>In the three panels (Cropland / Forest / Grassland), nitrogen addition lowers diversity everywhere, and each panel carries its own Tukey letters (a/b/c) derived from the emmeans simple effects with a shared df = 171. Notice the Grassland panel: its control is the highest of all (about 3.2) and it drops the most steeply — that’s exactly where the interaction comes from.</p><p>— -</p><p>## Going further: visualizing the interaction</p><p>An interaction is hard to convey with words alone, and an **interaction plot** is a great companion visualization — it connects the mean of each factor combination into lines. One caution: **non-parallel lines hint that an interaction might exist, but whether it truly exists is decided by the F-test on the interaction term** (our `Nlevel:Ecosystem` term, p = 0.0055). The plot is for display, not for formal testing:</p><p>```r</p><p><em># Compute group means</em></p><p><em>mu &lt;- aggregate(Shannon ~ Nlevel + Ecosystem, data = dat, FUN = mean)</em></p><p><em># Interaction plot: parallel vs non-parallel lines reflect the interaction</em></p><p><em>p_interact &lt;- ggplot(mu, aes(x = Nlevel, y = Shannon,</em></p><p><em>group = Ecosystem, color = Ecosystem)) +</em></p><p><em>geom_point(size = 2.2) +</em></p><p><em>geom_line(linewidth = 0.7) +</em></p><p><em>scale_color_manual(values = c(Grassland = “#2C7A57”, Forest = “#7A4D8E”,</em></p><p><em>Cropland = “#B85C4A”)) +</em></p><p><em>labs(x = “Nitrogen addition level”, y = “Mean Shannon diversity index”) +</em></p><p><em>theme_classic(base_size = 8, base_family = “Arial”) +</em></p><p><em>theme(axis.line = element_line(linewidth = 0.4),</em></p><p><em>axis.ticks = element_line(linewidth = 0.4),</em></p><p><em>panel.grid = element_blank())</em></p><p>```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RJJuNazUxVKxUqUEy-Weqg.png" /></figure><p>All three lines slope downward but they are **not parallel**. The green Grassland line is the steepest (falling from about 3.10 to 1.87), while the Forest (purple) and Cropland (red-brown) lines are nearly parallel and decline more gently (roughly 2.80 → 2.01 and 2.53 → 1.72). Because grassland drops the most, the interaction term is significant. In a real study, a pattern like this suggests grassland plant communities may be the most nitrogen-sensitive, and you’d interpret it in light of your experimental design.</p><p>### Reporting simple effects after a significant interaction</p><p>A significant interaction means nitrogen’s effect depends on the ecosystem, so reporting the Nlevel main effect alone is not very meaningful. The correct move is to **fix Ecosystem and use `emmeans` to compute simple effects on the full model** — that is, compare the Nlevel groups *within a given ecosystem*:</p><p>```r</p><p><em>library(emmeans)</em></p><p><em>fit2b &lt;- aov(Shannon ~ Nlevel * Ecosystem, data = dat)</em></p><p><em>emm &lt;- emmeans(fit2b, pairwise ~ Nlevel | Ecosystem, adjust = “tukey”)</em></p><p><em>emm$contrasts</em></p><p>```</p><p>Example output (partial):</p><p>```</p><p><em>Ecosystem = Grassland:</em></p><p><em>contrast estimate SE df t.ratio p.value</em></p><p><em>Control — Low_N 0.732 0.0904 171 8.097 &lt;0.0001</em></p><p><em>Control — High_N 1.225 0.0904 171 13.548 &lt;0.0001</em></p><p><em>Low_N — High_N 0.493 0.0904 171 5.450 &lt;0.0001</em></p><p>```</p><p>`emmeans` uses a **single shared residual variance and degrees of freedom (df = 171)** across all three ecosystems — the same error estimate for every panel. That’s more rigorous than splitting the data into subsets and running separate ANOVAs, which use each subset’s own residual df, don’t fully exploit the full-model information, and bring multiple-comparison problems across ecosystems. **In a research paper, for between-group comparisons after a significant interaction, the emmeans-style approach is what’s recommended.** Report the pairwise comparison table (estimate, SE, df, adjusted p-values) and the interaction plot as your primary results; the letter labels on the boxplot are just a visualization aid.</p><p>— -</p><p>## Interpreting the results</p><p>Putting the analysis and the figures together, we get three layers of conclusions:</p><p>**1. Nitrogen addition broadly suppresses diversity.** The single-factor ANOVA (F = 125.2, p &lt; 0.001) shows nitrogen level significantly affects Shannon diversity (the Nlevel main effect in the two-way model is also significant, F = 164.3, p &lt; 0.001, though it must be read in the context of the interaction — see point 3). The Tukey multiple comparisons show all three pairs differ significantly, the boxplot letters a/b/c are all different (different letters = significant difference), and the High_N group sits about 0.94 below Control. The direction matches the classic ecological conclusion that nitrogen deposition suppresses plant diversity.</p><p>**2. Ecosystems differ fundamentally.** Regardless of nitrogen level, Grassland has the highest overall diversity, Forest is intermediate, and Cropland is lowest, with the Ecosystem main effect highly significant (F = 21.7, p &lt; 0.001). This gradient fits the well-known observation that intensive agricultural management reduces plant diversity — long-term cultivation, weeding, and fertilization suppress the establishment of non-target species and push community composition toward a few species.</p><p>**3. The interaction reveals different responses.** The significant interaction (F = 3.80, p = 0.0055) shows nitrogen’s effect is *not* uniform: from the interaction plot, the Grassland line drops most steeply while Forest and Cropland decline gently and nearly in parallel — the interaction is driven mainly by grassland’s steeper response. If you saw a similar interaction in your own data, it would hint that grassland ecosystems face a greater risk of diversity loss under nitrogen-deposition scenarios.</p><p>&gt; **How to read Tukey letters:** the letters at the top of each box come from the post-hoc grouping — groups sharing the same letter don’t differ significantly, groups with different letters do. Since our three groups carry a, b, and c (all different), every pairwise difference reaches significance.</p><p>— -</p><p>## Practical tips</p><p>**`aov` formula quick reference:**</p><p>| Formula | Meaning |</p><p>| — — — | — — — |</p><p>| `aov(y ~ A)` | Single-factor ANOVA |</p><p>| `aov(y ~ A + B)` | Two-way main-effects model |</p><p>| `aov(y ~ A * B)` | Two-way interaction model (equivalent to `A + B + A:B`) |</p><p>**Common pitfalls to avoid:**</p><p>- **Check the residuals, not the raw data.** Running Shapiro-Wilk on the raw observations often falsely reports non-normality. ANOVA’s normality assumption applies to the model residuals, not to the observed values.</p><p>- **Check the assumptions on the final model.** A one-way and a two-way ANOVA are different models; each needs its own residual diagnostics. Don’t “check once and be done.”</p><p>- **Use Levene, not Bartlett, for variance.** `car::leveneTest()` centers on the median (Brown-Forsythe type) and is more robust to non-normal data than Bartlett.</p><p>- **”p &gt; 0.05&quot; means “no evidence to reject,” not “proven true.”** The assumption tests have the assumption as the null; a large p simply fails to reject. With big sample sizes, Shapiro-Wilk becomes sensitive to tiny deviations, so combine it with a Q-Q plot.</p><p>- **Locate significance with post-hoc tests.** A significant ANOVA only tells you “there is a difference”; to know *which* groups differ you must look at `TukeyHSD` or another post-hoc test.</p><p>- **Tukey letters are one common annotation style.** Use `multcompView::multcompLetters()` to turn post-hoc results into a/b/c letters on the boxplot; different letters mean significant differences. It’s common in ecology and agronomy papers (not a journal-mandated standard — some journals prefer directly reporting adjusted p-values).</p><p>- **Use a gradient for dose-like factors.** When levels carry an ordering meaning (e.g., nitrogen at 0 / low / high), a light-to-dark gradient of one hue communicates “increasing dose” better than unrelated hues.</p><p>- **Be careful talking about main effects when the interaction is significant.** A significant interaction means one factor’s effect depends on the other, so main effects must be read in that context; after a significant interaction, use emmeans for simple effects.</p><p>- **Mind pseudoreplication.** If several quadrats come from the same site (nested or repeated-measures structure), they aren’t fully independent replicates, and ordinary ANOVA will inflate your effective sample size. Switch to a mixed-effects model, e.g., `lmer(Shannon ~ Nlevel * Ecosystem + (1 | Site), data = dat)`.</p><p>- **A non-significant interaction doesn’t force you to drop it.** Whether to simplify to the additive model depends on your design and pre-specified hypotheses — don’t delete terms mechanically just because p is large.</p><p>- **Handle unequal variances by design.** For a single factor use Welch ANOVA (`oneway.test()`); for a two-factor design don’t reach for Kruskal-Wallis — choose a robust, permutation, generalized, or mixed model suited to your design.</p><p>— -</p><p>## The complete runnable script</p><p>Here’s the full R script — copy it into RStudio and run it (the `anova_diversity.csv` data file should be in the same folder):</p><p>```r</p><p><em># ============================================================</em></p><p><em># Full workflow: single-factor &amp; two-way ANOVA</em></p><p><em># ============================================================</em></p><p><em># On first run, install packages:</em></p><p><em># install.packages(c(“car”, “ggplot2”, “multcompView”, “emmeans”))</em></p><p><em>library(car)</em></p><p><em>library(ggplot2)</em></p><p><em>library(multcompView) # Tukey letters</em></p><p><em>library(emmeans) # simple effects (between-group comparison after interaction)</em></p><p><em># — — Load data — -</em></p><p><em>dat &lt;- read.csv(“anova_diversity.csv”, header = TRUE)</em></p><p><em>dat$Ecosystem &lt;- factor(dat$Ecosystem)</em></p><p><em>dat$Nlevel &lt;- factor(dat$Nlevel, levels = c(“Control”, “Low_N”, “High_N”))</em></p><p><em>head(dat)</em></p><p><em># — — Unified theme (minimal publication style) — -</em></p><p><em>theme_pub &lt;- function(base_size = 8, base_family = “Arial”) {</em></p><p><em>theme_classic(base_size = base_size, base_family = base_family) +</em></p><p><em>theme(</em></p><p><em>axis.line = element_line(linewidth = 0.4, colour = “black”),</em></p><p><em>axis.ticks = element_line(linewidth = 0.4, colour = “black”),</em></p><p><em>axis.title = element_text(size = base_size + 1),</em></p><p><em>axis.text = element_text(size = base_size — 0.5),</em></p><p><em>legend.title = element_text(size = base_size),</em></p><p><em>legend.text = element_text(size = base_size — 1),</em></p><p><em>strip.text = element_text(size = base_size, face = “bold”),</em></p><p><em>legend.key.size = unit(3, “mm”),</em></p><p><em>panel.grid = element_blank()</em></p><p><em>)</em></p><p><em>}</em></p><p><em># Color palettes</em></p><p><em>cols_nlevel &lt;- c(Control = “#D6E4F0”, Low_N = “#5B8CC9”, High_N = “#1F3B73”)</em></p><p><em>cols_ecosystem &lt;- c(Grassland = “#2C7A57”, Forest = “#7A4D8E”, Cropland = “#B85C4A”)</em></p><p><em># ============================================================</em></p><p><em># Step 1: Assumption checks</em></p><p><em># ============================================================</em></p><p><em>fit1 &lt;- aov(Shannon ~ Nlevel, data = dat)</em></p><p><em>shapiro.test(residuals(fit1)) # normality (on residuals)</em></p><p><em>leveneTest(Shannon ~ Nlevel, data = dat) # homogeneity of variance</em></p><p><em># ============================================================</em></p><p><em># Step 2: Single-factor ANOVA + Tukey multiple comparisons</em></p><p><em># ============================================================</em></p><p><em>summary(fit1)</em></p><p><em>TukeyHSD(fit1)</em></p><p><em># ============================================================</em></p><p><em># Step 3: Two-way ANOVA (main effects vs interaction model)</em></p><p><em># ============================================================</em></p><p><em>fit2a &lt;- aov(Shannon ~ Nlevel + Ecosystem, data = dat)</em></p><p><em>summary(fit2a) # main-effects model</em></p><p><em>fit2b &lt;- aov(Shannon ~ Nlevel * Ecosystem, data = dat)</em></p><p><em>summary(fit2b) # interaction model</em></p><p><em># Note: when the interaction is significant, don’t do an overall Tukey on</em></p><p><em># Nlevel directly — use emmeans to look at simple effects within each Ecosystem</em></p><p><em># (see the two-way visualization section)</em></p><p><em># ============================================================</em></p><p><em># Step 4: Visualization</em></p><p><em># ============================================================</em></p><p><em># — — Tukey letter helper — -</em></p><p><em>tukey_letters &lt;- function(model, fac, data) {</em></p><p><em>tk &lt;- TukeyHSD(model)[[fac]]</em></p><p><em>lv &lt;- levels(data[[fac]])</em></p><p><em>pmat &lt;- matrix(1, length(lv), length(lv), dimnames = list(lv, lv))</em></p><p><em>for (pr in rownames(tk)) {</em></p><p><em>v &lt;- strsplit(pr, “-”)[[1]]</em></p><p><em>pmat[v[2], v[1]] &lt;- pmat[v[1], v[2]] &lt;- tk[pr, “p adj”]</em></p><p><em>}</em></p><p><em>multcompLetters(pmat)$Letters</em></p><p><em>}</em></p><p><em># Single-factor boxplot (with Tukey letters)</em></p><p><em>let1 &lt;- tukey_letters(fit1, “Nlevel”, dat)</em></p><p><em>lab1 &lt;- data.frame(Nlevel = names(let1), letters = let1,</em></p><p><em>y = tapply(dat$Shannon, dat$Nlevel, max) + 0.1)</em></p><p><em>p_oneway &lt;- ggplot(dat, aes(x = Nlevel, y = Shannon, fill = Nlevel)) +</em></p><p><em>geom_boxplot(alpha = 0.85, outlier.shape = NA, linewidth = 0.4) +</em></p><p><em>geom_jitter(width = 0.12, size = 0.6, alpha = 0.35, color = “grey35”) +</em></p><p><em>geom_text(data = lab1, aes(x = Nlevel, y = y, label = letters),</em></p><p><em>size = 3, fontface = “bold”) +</em></p><p><em>scale_fill_manual(values = cols_nlevel) +</em></p><p><em>labs(x = “Nitrogen addition level”, y = “Shannon diversity index”) +</em></p><p><em>theme_pub() +</em></p><p><em>theme(legend.position = “none”)</em></p><p><em># Two-way faceted boxplot (per-panel letters from emmeans simple effects, shared df=171)</em></p><p><em>emm &lt;- emmeans(fit2b, ~ Nlevel | Ecosystem)</em></p><p><em>ct &lt;- as.data.frame(contrast(emm, method = “pairwise”, adjust = “tukey”))</em></p><p><em>emmeans_letters &lt;- function(ct_df, fac_levels) {</em></p><p><em>pmat &lt;- matrix(1, length(fac_levels), length(fac_levels),</em></p><p><em>dimnames = list(fac_levels, fac_levels))</em></p><p><em>for (i in seq_len(nrow(ct_df))) {</em></p><p><em>nm &lt;- strsplit(as.character(ct_df$contrast[i]), “ — “)[[1]]</em></p><p><em>pmat[nm[2], nm[1]] &lt;- pmat[nm[1], nm[2]] &lt;- ct_df$p.value[i]</em></p><p><em>}</em></p><p><em>multcompLetters(pmat)$Letters</em></p><p><em>}</em></p><p><em>let2 &lt;- lapply(levels(dat$Ecosystem), function(ec)</em></p><p><em>emmeans_letters(ct[ct$Ecosystem == ec, ], levels(dat$Nlevel)))</em></p><p><em>names(let2) &lt;- levels(dat$Ecosystem)</em></p><p><em>lab2 &lt;- do.call(rbind, lapply(names(let2), function(ec) {</em></p><p><em>data.frame(Ecosystem = ec, Nlevel = names(let2[[ec]]), letters = let2[[ec]],</em></p><p><em>y = tapply(dat$Shannon[dat$Ecosystem == ec],</em></p><p><em>dat$Nlevel[dat$Ecosystem == ec], max) + 0.12)</em></p><p><em>}))</em></p><p><em>p_twoway &lt;- ggplot(dat, aes(x = Nlevel, y = Shannon, fill = Nlevel)) +</em></p><p><em>geom_boxplot(alpha = 0.85, outlier.shape = NA, linewidth = 0.4) +</em></p><p><em>geom_jitter(width = 0.12, size = 0.6, alpha = 0.35, color = “grey35”) +</em></p><p><em>geom_text(data = lab2, aes(x = Nlevel, y = y, label = letters),</em></p><p><em>size = 3, fontface = “bold”) +</em></p><p><em>facet_wrap(~ Ecosystem, ncol = 3) +</em></p><p><em>scale_fill_manual(values = cols_nlevel) +</em></p><p><em>labs(x = “Nitrogen addition level”, y = “Shannon diversity index”) +</em></p><p><em>theme_pub() +</em></p><p><em>theme(legend.position = “none”)</em></p><p><em># Interaction plot</em></p><p><em>mu &lt;- aggregate(Shannon ~ Nlevel + Ecosystem, data = dat, FUN = mean)</em></p><p><em>p_interact &lt;- ggplot(mu, aes(x = Nlevel, y = Shannon,</em></p><p><em>group = Ecosystem, color = Ecosystem)) +</em></p><p><em>geom_point(size = 2.2) +</em></p><p><em>geom_line(linewidth = 0.7) +</em></p><p><em>scale_color_manual(values = cols_ecosystem) +</em></p><p><em>labs(x = “Nitrogen addition level”, y = “Mean Shannon diversity index”) +</em></p><p><em>theme_pub()</em></p><p><em># Save plots</em></p><p><em>ggsave(“boxplot_oneway.png”, p_oneway, width = 110, height = 100, units = “mm”, dpi = 300)</em></p><p><em>ggsave(“boxplot_twoway.png”, p_twoway, width = 183, height = 90, units = “mm”, dpi = 300)</em></p><p><em>ggsave(“interaction_plot.png”, p_interact, width = 120, height = 100, units = “mm”, dpi = 300)</em></p><p>```</p><p>**To adapt this to your own data:**</p><p>1. Prepare a CSV: factor (categorical) columns followed by your continuous response as the last column.</p><p>2. Convert the factor columns with `dat$Group &lt;- factor(dat$Group)`.</p><p>3. Replace the file name in `read.csv()` and the variable names in the formulas (e.g., `aov(value ~ Group)`).</p><p>4. If your single-factor variances aren’t equal, switch to `oneway.test(Shannon ~ Nlevel, data = dat)` (Welch ANOVA); for an unequal-variance two-factor design, choose a robust method suited to your study design.</p><p>— -</p><p>And there you have it — a full ANOVA workflow in R, from assumption checks through single- and two-way models to emmeans simple effects after a significant interaction. The code is yours to reuse on your own data. If it saved you a headache, give this post a few claps 👏 and drop a comment if you have any questions. And follow along for more hands-on R tutorials for ecologists and data scientists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8ef7a126660" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>