Core tidyverse verbs: filter, select, mutate, group_by/summarise, pivot_wider/longer. The most common data manipulation operations in ecology.
# ── dplyr essentials ──────────────────────────────────────────
library(dplyr); library(tidyr)
# filter rows
iris |> filter(Species == "setosa", Sepal.Length > 5)
# select columns
iris |> select(Species, starts_with("Sepal"))
# mutate (add/transform columns)
iris |> mutate(sepal_ratio = Sepal.Length / Sepal.Width)
# group_by + summarise
iris |>
group_by(Species) |>
summarise(mean_SL = mean(Sepal.Length),
sd_SL = sd(Sepal.Length),
n = n())
# arrange
iris |> arrange(desc(Sepal.Length)) |> head(5)
# rename
iris |> rename(sp = Species)
# ── tidyr ──────────────────────────────────────────────────────
df <- data.frame(species = c("A","A","B","B"),
trait = c("BL","BD","BL","BD"),
value = c(10,5,8,4))
# pivot_wider (long → wide)
df |> pivot_wider(names_from = trait, values_from = value)
# pivot_longer (wide → long)
iris |> pivot_longer(cols = -Species, names_to = "trait", values_to = "value")
# drop_na / replace_na
iris |> drop_na()
iris |> replace_na(list(Sepal.Length = 0))
# left_join
sp_info <- data.frame(Species = c("setosa","versicolor","virginica"),
group = c("A","B","B"))
iris |> left_join(sp_info, by = "Species") |> head(3)