dplyr summarise() 深入解析:分组汇总的边界规则、错误机制与 reframe() 迁移指南

原创2026-10-13 22:48:161,357 阅读
文章标签:数据分析

dplyr summarise() 深入解析:分组汇总的边界规则、错误机制与 reframe() 迁移指南

本篇文章基于 dplyr 仓库中 summarise() 的官方文档 与快照测试 tests/testthat/_snaps/summarise.md,系统梳理 summarise() 的完整行为契约:从“每组一行”的核心语义、.groups 分组结构的默认行为,到非汇总结果必须迁移至 reframe()、.by 与 .groups 的互斥规则,再到其精心设计的错误消息体系。读完本文,你将理解 summarise() 的每一条边界规则、背后的源码实现(含 C++ 校验逻辑),并能在实际项目中写出不会踩坑的汇总代码。

一、核心语义:把每个分组压成一行

summarise() 会创建一个新的数据框:对于每个分组变量组合返回一行;若输入没有分组变量,则返回单行,对全部观测做汇总。输出中包含每个分组变量一列,以及你指定的每个汇总统计量一列。summarise() 与 summarize() 是完全同义的,两者只是美式/英式拼写差异(见 R/summarise.R 中的 summarize <- summarise)。

官方文档(man/summarise.Rd)给出了最常用的汇总函数清单:

用途 推荐函数
中心趋势(Center) mean()、median()
离散程度(Spread) sd()、IQR()、mad()
范围(Range) min()、max()
位置(Position) first()、last()、nth()
计数(Count) n()、n_distinct()
逻辑判断(Logical) any()、all()

基本用法如下:

# 未分组:单行汇总
mtcars |>
  summarise(mean = mean(disp), n = n())

# 先分组再汇总:每组一行
mtcars |>
  group_by(cyl) |>
  summarise(mean = mean(disp), n = n())

# 每次汇总会剥掉一层分组(该分组此时只剩一行)
mtcars |>
  group_by(cyl, vs) |>
  summarise(cyl_n = n()) |>
  group_vars()

1.1 返回值的三条硬性规则

从文档的 @returns 与源码 summarise_build()(R/summarise.R)可以确认输出的构成:

  • 行来自底层分组键(group_keys(),见 R/group-data.R 的 group_keys0());
  • 列是分组键与汇总表达式的组合;
  • 分组结构由 .groups 参数控制,输出可能是 grouped_df、tibble 或 rowwise_df;
  • 数据框的属性不会被保留,因为 summarise() 本质上是创建一个全新的数据框(测试 test-summarise.R 中 "doesn't preserve attributes" 与 "strips off subclass" 两个用例对此有专门断言,见 tests/testthat/test-summarise.R)。

二、.groups 参数:输出结果的分组结构

.groups 目前标注为 experimental,控制汇总结果的分组结构,可取四个值:

取值 含义
"drop_last" 丢弃最后一层分组。这是 1.0.0 之前唯一支持的选项
"drop" 丢弃所有层级的分组
"keep" 与输入 .data 保持相同的分组结构
"rowwise" 每一行自成一组

当 .groups 未指定时:对分组数据框默认 "drop_last",对 rowwise 数据框默认 "keep"。同时,除非结果未分组、或全局选项 dplyr.summarise.inform 被设为 FALSE、或 summarise() 是在某个包的函数内部被调用,否则会打印一条消息告知结果的分组方式。

2.1 默认行为与提示消息(快照实证)

快照文件 tests/testthat/_snaps/summarise.md 忠实记录了这些默认行为:

  • 对 group_by(df, x) 汇总且只有一层分组时,结果被完全解组,不打印任何消息;
  • 对 group_by(df, x, y) 汇总时,打印消息说明“已重新分组”:
`summarise()` has regrouped the output.
i Summaries were computed grouped by x and y.
i Output is grouped by x.
i Use `summarise(.groups = "drop_last")` to silence this message.
i Use `summarise(.by = c(x, y))` for per-operation grouping (`?dplyr::dplyr_by`) instead.
  • 对 rowwise(df, x, y) 汇总时,消息说明输出已从 rowwise 转为分组数据框:
`summarise()` has converted the output from a rowwise data frame to a grouped data frame.
i Summaries were computed rowwise.
i Output is grouped by x and y.
i Use `summarise(.groups = "keep")` to silence this message.

2.2 消息的触发条件:源码级解析

消息是否打印由 summarise_verbose()(R/summarise.R)决定,逻辑如下:

  1. 用户显式提供了 .groups → 不打印(return(FALSE));
  2. 否则读取全局选项 dplyr.summarise.inform,若为 TRUE/FALSE 则直接采用;
  3. 否则仅当调用环境是全局环境(topenv(.env) 与 global_env() 一致)时才打印——这就是“包内调用不打印消息”的实现来源。

两条消息分别由 inform_implicit_drop_last_for_grouped_df() 与 inform_implicit_keep_for_rowwise_df() 生成(R/summarise.R)。注意:分组数据框仅在 length(old_groups) > 1 时才会提示(因为一层分组解组后结果已未分组、无需提示),rowwise 则仅在 length(old_groups) > 0 时提示。

快照中的 "summarise() respects dplyr.summarise.inform = FALSE" 一节验证了通过 local_options(dplyr.summarise.inform = FALSE) 后即使强制在全局环境求值也不再输出消息,对应测试见 tests/testthat/test-summarise.R。

2.3 非法取值时报错

如果 .groups 不是合法取值,源码会直接报错并列出可选值(R/summarise.R):

# Error:
# ! `.groups` can't be "foo".
# i Possible values are NULL (default), "drop_last", "drop", "keep", and "rowwise"

三、非汇总结果已被移除:统一改投 reframe()

这是 summarise() 当前版本最重要的行为边界。历史上 summarise() 曾允许每个分组返回任意长度,但从 dplyr 1.1.0 起,返回 0 行或大于 1 行的行为先被弃用(见 NEWS.md 中 "Returning more or less than 1 row per group in summarise(). Deprecated in 1.1.0 (Jan 2023), use reframe() instead." 与 #6382, #7761),当前版本已直接报错(defunct)。

快照文件完整记录了这些报错形态:

# 未分组输入,返回 2 个值
summarise(df, x = which(x < 3))
# Error in `summarise()`:
# i In argument: `x = which(x < 3)`.
# Caused by error:
# ! `x` must be size 1, not 2.
# i To return more or less than 1 row per group, use `reframe()`.

# 分组输入,第二组返回 0 个值
summarise(gf, x = seq_len(a), y = 1)
# Error in `summarise()`:
# i In argument: `x = seq_len(a)`.
# i In group 2: `a = 2`.
# Caused by error:
# ! `x` must be size 1, not 2.

# rowwise 输入,某行返回 0 个值
summarise(rdf, x = which(x < 3))
# i In row 3.
# ! `x` must be size 1, not 0.

注意一个细节:summarise(tibble(), x = 1, y = 1:3, z = 1) 中即使 x、z 都是合法的大小 1 结果,也会因为 y 不合规而整体报错,说明每个表达式的每个分组结果都必须为 size 1。

3.1 底层实现:C++ 层的全量校验

这个 size 1 约束并非 R 层软检查,而是在 C++ 层对每个表达式、每个分组逐一校验。dplyr_summarise_check_all_size_one()(src/summarise.cpp)遍历 result_per_group_per_expression,只要某个分组结果 vctrs::short_vec_size(result) != 1,就调用 stop_summarise_incompatible_size(i, j, result_size) 抛出 dplyr:::summarise_incompatible_size 条件对象。R 侧 summarise_cols()(R/summarise.R)在汇总模式下调用该校验,summarise_bullets() 再把它格式化成我们看到的错误消息(R/summarise.R)。

值得对比的是:同一套 summarise_cols() 也被 reframe() 复用,但传参 verb = "reframe" 时改走 dplyr_reframe_recycle_horizontally_in_place()(src/summarise.cpp),不再要求 size 1,而是把每组内各表达式水平回收成公共大小,随后用 group_sizes 重复分组键。这就是 reframe() 与 summarise() 共享评估管线却行为迥异的原因。

3.2 需要多行结果时怎么办:reframe()

reframe()(R/reframe.R)与 summarise() 有两点关键差异:

  • 每个分组可返回任意行数,而 summarise() 必须压到一行;
  • reframe() 的输出永远未分组,而 summarise() 可能返回分组或 rowwise 数据框。
# 返回每组内满足条件的多个值
df |>
  group_by(g) |>
  reframe(x = intersect(x, table))

# 每个分组可以返回不同行数
df |>
  reframe(x = intersect(x, table), .by = g)

# 一个表达式返回多列
starwars |>
  reframe(
    across(c(height, mass), quantile_df, .unpack = TRUE),
    .by = homeworld
  )

四、.by 与 .groups 的互斥规则

.by 是 dplyr 1.1.0 引入的单次操作分组(per-operation grouping)参数(见 NEWS.md)。summarise() 的 .by 采用 tidy-select 语法选择分组列,与 group_by() 的 data-masking 语义不同,且分组只影响当前这一次操作。

快照文件记录了三条 .by 相关硬性规则:

# 1. 不能同时提供 .by 和 .groups
summarise(df, .by = x, .groups = "drop")
# Error:
# ! Can't supply both `.by` and `.groups`.

# 2. 不能对分组数据框使用 .by
summarise(gdf, .by = x)
# Error:
# ! Can't supply `.by` when `.data` is a grouped data frame.

# 3. 不能对 rowwise 数据框使用 .by
summarise(rdf, .by = x)
# Error:
# ! Can't supply `.by` when `.data` is a rowwise data frame.

第一条规则在泛型函数 summarise() 入口就做了拦截(R/summarise.R),后两条由 check_by() 实现(R/by.R)。compute_by()(R/by.R)根据输入类型决定分组模式:对未分组数据框且 .by 非空时,用 vec_group_loc() 计算分组(compute_by_groups,R/by.R)。

4.1 为什么推荐 .by?

对比表(来源 man/rmd/by.Rmd):

.by group_by()
分组只影响单个动词 分组在多个动词间持久生效
用 tidy-select 选择变量 用 data-masking 计算表达式
汇总按“首次出现”保持原顺序 汇总按键值升序排序

.by 的最大收益是无需事后 ungroup()、也永远不会收到 .groups 提示消息;同时保持数据原有顺序(不按键值排序)。若需要排序,显式使用 arrange() 即可。测试 "transient grouping orders by first appearance"(tests/testthat/test-summarise.R)验证了 .by 分组按首次出现顺序输出。

五、输入数据框的命名检查

快照文件记录了三条命名相关错误(issue #6758):

# 列名为 "" 
summarise(df1)
# ! Can't transform a data frame with `NA` or `""` names.

# 列名为 NA
summarise(df2)
# ! Can't transform a data frame with missing names.

# 重复列名
summarise(tibble(x = 1, x = 1, .name_repair = "minimal"), x)
# ! Can't transform a data frame with duplicate names.

对应测试见 tests/testthat/test-summarise.R 与 "summarise() gives meaningful errors" 中的重复列名用例。这是对输出列名完整性的保护——因为 summarise() 生成的新数据框必须拥有可用的列名,缺失或重复的列名会破坏结果结构。

六、有意义的错误消息体系

快照文件最后一大节 "summarise() gives meaningful errors" 集中展示了 dplyr 在错误诊断上的投入,这也是 summarise() 最值得称道的工程细节之一。错误消息统一遵循三段式结构:入口(Error in \summarise()`)→ 上下文(In argument:/In group:/In row:)→ 根因(Caused by error:`)。

6.1 不支持的结果类型

summarise(tibble(x = 1), a = rlang::env(a = 1))
# i In argument: `a = rlang::env(a = 1)`.
# Caused by error:
# ! `a` must be a vector, not an environment.

summarise(rowwise(tibble(...)), a = lm(y ~ x))
# ! `a` must be a vector, not a <lm> object.
# i Did you mean: `a = list(lm(y ~ x))` ?

汇总结果必须是向量(vctrs 意义上的 vector)。试图在分组数据框里返回一个 lm 对象会收到贴心提示——用 list() 包裹即可。C++ 侧 dplyr_mask_eval_all_summarise()(src/summarise.cpp)在每个分组求值后立即调用 vctrs::obj_is_vector() 检查,不满足即抛出 dplyr:::summarise_unsupported_type;R 侧 summarise_bullets 对应方法生成消息(R/summarise.R)。

6.2 跨组类型不兼容

summarise(group_by(tibble(id = 1:2, a = list(1, "2")), id), a = a[[1]])
# ! `a` must return compatible vectors across groups.
# i Result of type <double> for group 1: `id = 1`.
# i Result of type <character> for group 2: `id = 2`.

各组结果最终要用 vctrs::vec_c() 合并,类型必须可兼容(可公共强转)。快照还验证了正向情况:summarise 会把 NA 与字符串、整数与浮点数跨组统一强转(测试 "summarise coerces types across groups",tests/testthat/test-summarise.R)。

6.3 NULL 与混合 NULL

summarise(group_by(data.frame(x = 1:2, g = 1:2), g), x = if (g == 1) 42)
# ! `x` must return compatible vectors across groups.
# x Can't combine NULL and non NULL results.

当所有分组都返回 NULL 时结果会被静默跳过(summarise(df, x = NULL) 等价于 summarise(df),测试 "summarise() silently skips when all results are NULL (#5708)");但只要混入了非 NULL 结果就报错。C++ 侧统计 n_null,若 0 < n_null < ngroups 则定位到第一个返回 NULL 的分组并抛出 dplyr:::summarise_mixed_null(src/summarise.cpp)。

6.4 .data 代词与列不存在

summarise(tibble(a = 1), c = .data$b)
# Caused by error in `.data$b`:
# ! Column `b` not found in `.data`.

使用 .data 代词访问不存在的列会得到明确的错误定位,分组场景下还会附上当前分组键。

6.5 表达式内部错误与错误上下文定位

summarise(tibble(), stop("{"))          # i In argument: `stop("{")`.
summarise(group_by(tibble(a = 1, b = "{value:1, unit:a}"), b), a = stop("!"))
# i In argument: `a = stop("!")`.
# i In group 1: `b = "{value:1, unit:a}"`.

即使表达式内部报错,错误消息也会被包装上“第几个参数、哪个分组”的上下文,且不会把用户消息内容当作 glue 模板二次插值(测试注释 "Not glue()ing")。这背后是 DataMask 与 local_error_context()/poke_error_context() 机制(R/summarise.R)——每个表达式求值时都会记录当前的参数序号与分组上下文,C 层错误对象携带 index_expression、index_group、actual_size 等结构化字段(src/summarise.cpp),R 侧据此重建出完整的分组定位信息。

6.6 不能覆盖列的活动绑定(#6666)

summarise(df, y = {
  x <<- x + 2L
  mean(x)
})
# Error in `summarise()`:
# i In argument: `y = { ... }`.
# Caused by error:
# ! unused argument (base::quote(3:6))

使用 <<- 试图在汇总中修改原始列(活动绑定 active binding)会报错;而使用局部赋值 <- 则安全(仅作用于表达式内部,不影响数据掩码)。两个行为分别由测试 "can't overwrite column active bindings (#6666)" 与 "assigning with \<-` doesn't affect the mask (#6666)"` 锁定(tests/testthat/test-summarise.R)。

七、后端差异与实战注意事项

文档 Backend variations 一节(man/summarise.Rd)强调:数据框后端支持在同一个 summarise() 内引用刚创建的汇总变量(如同 mutate()),例如:

summarise(group_by(df, x), y = mean(x), z = y + 1)

但这也带来一个陷阱:同名汇总变量会覆盖之前的变量,使其对后续表达式不可见:

# BEWARE: 第二个 disp 已被第一个 disp 覆盖,sd() 算的是新列!
mtcars |>
  group_by(cyl) |>
  summarise(disp = mean(disp), sd = sd(disp))

在 SQL 等其它后端中这种“后定义覆盖”可能不被支持,因此文档建议优先为汇总变量使用全新名字。测试 "can use freshly create variables (#138)"(tests/testthat/test-summarise.R)验证了引用新变量的正确路径。

此外还有几个实战细节值得记住:

  • 列表列:summarise() 支持返回列表列(y = list(x)),且 rowwise 模式下会用 <a href="https://link.gitcode.com/i/22e606dafe61c2c7ca2b4339ed642491" target="_blank">[ 而非 [ 提取,便于嵌套模型等场景(见 [R/rowwise.R 的 List-columns 说明);
  • 未命名单行数据框会自动展开为多列:summarise(df, tibble(y = x * 2, z = 3)) 会得到 y、z 两列;命名后(df = tibble(...))则打包为单列。测试 "unnamed tibbles are unpacked (#2326)" / "named tibbles are packed (#2326)" 见 tests/testthat/test-summarise.R;
  • 零行/空列输入:summarise() 对 0 行、0 列输入均有正确行为(tests/testthat/test-summarise.R),分组数据框还能为因子中未出现的零长度分组保留一行(.drop = FALSE 场景)。

八、快照测试:行为契约的守护者

本文主体所依据的 tests/testthat/_snaps/summarise.md 是 testthat 的快照测试产物:测试代码中的 expect_snapshot()(如 tests/testthat/test-summarise.R)会把命令输出与这个 Markdown 文件逐字比对,一旦错误消息文案、分组提示或输出结构发生变化,测试即失败。因此这份快照文件既是“历史行为的冻结记录”,也是开发者修改 summarise() 时必须同步更新的契约清单。对使用者而言,它则是一份极其可靠的“错误消息百科”——你实际运行时看到的每一条提示,都应与这里的内容一致。

总结

summarise() 的设计哲学可以概括为“用严格的约束换取确定性”:

  • 每个分组、每个表达式必须返回 size 1 的向量或单行数据框,否则报错并引导使用 reframe();
  • .groups 决定输出分组结构,默认 "drop_last"(分组)/ "keep"(rowwise),消息可用 dplyr.summarise.inform = FALSE 或显式 .groups 关闭;
  • .by 提供单次操作分组,但与 .groups 互斥,且禁止用于已分组/rowwise 数据框;
  • 输入列名必须完整无重复;
  • 所有失败都会获得带参数序号、分组键或行号的三段式诊断消息,并由 src/summarise.cpp 的 C++ 校验层与 R/summarise.R 的 bullets 机制协同生成。

当你需要每组返回多行(如分位数、交集、嵌套模型输出)时,请果断选择 reframe();当你只需要每组合并成一个数值时,summarise() 依然是 dplyr 中最可靠、最不易出错的聚合入口。

登录后查看全文
dplyr