Post #2272758
2026-05-08 19:50 UTC
I like the new .by= option for pre-group operations in #rstats, but further operations after summarise() require the group_by() option.
# This will correctly calculate the percent
# of species on each island
df <- palmerpenguins(penguins)
df |>
group_by(species, island) |>
summarise(n=n()) |>
mutate(Pct = n / sum(n)) |>
ungroup()
# This does the percent of each island-
# species combo
df |>
summarise(n=n(), .by =c(species, island) ) |>
mutate(Pct = n / sum(n))
Replies (1)
-
@Lluis_Revilla@fosstodon.org 2026-05-08 21:29
@DataAngler@vis.social mutate and filter also have the .by argument: df |> summarise(.by = c(species, island), n=n()) |> mutate(.by = species, Pct = n/sum(n)) The only difference is the order TIL that dplyr will warn about grouped operations and further operations that are ungrouped: From your first example: `summarise()` has regrouped the output. ℹ Summaries were computed grouped by species and island. ℹ Output is grouped by species. ℹ Use `summarise(.groups = "drop_last")` to silence this message.