You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用group_by()多列分组并对其余列求和

按Date和Participant Code分组求和的实现方案

问题背景

需对tibble格式的all_ergo数据,按Date和Participant Code两列分组,对其余所有数值列执行求和操作,已掌握单分组代码但不清楚如何扩展为双列分组。

数据预览

head(all_ergo)
# A tibble: 6 × 10
  Date       time_bike distance bike_calories   power `Participant Code` time_active time_total desk_ca…¹ total…²
  <date>         <dbl>    <dbl>         <dbl>   <dbl> <chr>                    <dbl>      <dbl>     <dbl>   <dbl>
1 2022-04-12       120        0             0 0.00613 AE1_01                     360        360      11.0    11.0
2 2022-04-12       120        0             0 0.00613 AE1_01                    1920       1920      58.6    58.6
3 2022-04-12       120        0             0 0.00613 AE1_01                    3480       3480     106.    106. 
4 2022-04-12       120        0             0 0.00613 AE1_01                    3540       3540     108.    108. 
5 2022-04-12       120        0             0 0.00580 AE1_01                     360        360      11.0    11.0
6 2022-04-12       120        0             0 0.00580 AE1_01                    1920       1920      58.6    58.6
# … with abbreviated variable names ¹​desk_calories, ²​total_calories

需求说明

按Date和Participant Code双列分组,对其余所有列执行求和操作。

现有单分组代码

Summary_PRE <- workday_PRE%>% group_by(Date) %>% mutate_if(is.character,as.numeric) %>% summarise(across(Axis1:Counter,sum))
Summary_PRE <- subset (Summary_PRE, select = -c(Axis1,Axis2,Axis3,VM))

解决方案

只需在group_by()中同时传入两个分组列名(用逗号分隔)即可,针对你的数据场景,优化后的代码如下:

Summary_ERGO <- all_ergo %>%
  # 同时指定两个分组列,含空格的列名用反引号包裹
  group_by(Date, `Participant Code`) %>%
  # 对所有数值列求和,分组列自动保留在结果中
  summarise(across(where(is.numeric), sum), .groups = "drop")

代码说明:

  • group_by(Date, Participant Code):双列分组的核心写法,列名包含空格时必须用反引号包裹
  • across(where(is.numeric), sum):自动识别所有数值类型列并求和,无需手动指定列范围
  • .groups = "drop":求和完成后取消分组状态,返回普通tibble,避免后续操作受分组限制

如果需要先将字符型列转换为数值型,可保留原代码中的转换步骤:

Summary_ERGO <- all_ergo %>%
  mutate_if(is.character, as.numeric) %>%
  group_by(Date, `Participant Code`) %>%
  summarise(across(where(is.numeric), sum), .groups = "drop")

内容的提问来源于stack exchange,提问作者Richard Michaud Langis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 08:25:01