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

在R的dplyr中分组汇总后保留对应price列的实现问题

在dplyr分组汇总时保留对应price列的解决方法

你当前的代码按category分组合并type为cars列,但未保留对应的price列。根据示例数据,同一category下的price是唯一值,只需在summarise步骤中添加获取该组price的逻辑即可。

修改后的代码

library(tidyverse)

df <- tibble(type=c("Jeep","Ferrari", "Fiat","Lancia", "Bentley"), 
             category=c("expensive", "expensive", "cheap","cheap","unapproachable"),
              price=c(100,100,20,20,1000))

df  |> 
  group_by(category) |> 
  summarise(
    cars = toString(sort(unique(type))),
    price = unique(price), # 获取该组唯一的price值
    .groups='drop'
  )

运行结果

# A tibble: 3 × 3
  category       cars          price
  <chr>          <chr>         <dbl>
1 cheap          Fiat, Lancia     20
2 expensive      Ferrari, Jeep    100
3 unapproachable Bentley        1000

补充说明

由于每个category对应的price完全一致,除了unique(price),你也可以用first(price)、last(price)、min(price)或max(price)来获取价格,结果完全相同。如果后续业务场景中同一category可能出现不同price值,需根据实际需求(如取平均值、总和等)调整这部分逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:45:49