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

如何按no分组对tibble中bar开头列求和并保留其他列?

解决方案

可以使用dplyr包的分组与批量列操作实现需求,代码如下:

library(dplyr)

# 构造原始数据
data <- tibble(no = c(1,2,3,3), foo = c(4, 5, 6, 6), bar_1 = c(5, 6, 7, 3), bar_2 = c(4, 3, 6, 8))

# 分组计算
result <- data %>%
  group_by(no) %>%
  summarise(
    # 保留非bar开头的列(同组内值一致,取第一个即可)
    foo = first(foo),
    # 对所有以bar开头的列求和
    across(starts_with("bar"), sum)
  ) %>%
  ungroup()

# 查看结果
print(result)

运行后得到的结果与预期一致:

# A tibble: 3 × 4
     no   foo bar_1 bar_2
  <dbl> <dbl> <dbl> <dbl>
1     1     4     5     4
2     2     5     6     3
3     3     6    10    14

关键点说明

  • group_by(no):按no列完成分组
  • first(foo):同一no分组内的foo值完全相同,用first()提取该组值以保留原数据状态
  • across(starts_with("bar"), sum):通过starts_with("bar")匹配所有以bar开头的列,批量对这些列执行求和操作

内容的提问来源于stack exchange,提问作者Simon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 13:09:59