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

R语言summarize函数异常求助:无法正确生成分组利润率统计

问题分析与解决方法
  • 核心问题:你未将orders与types数据集通过Product字段关联,直接调用types$Cost Per Cookie``会按位置循环匹配数据,而非按产品对应匹配,导致计算出的prof和rev是每行单独值;同时summarize未对组内数据求和,最终得到多个百分比值。

  • 修正后的代码:

orders <- read_excel("Orders.xlsx")
customers <- read_excel("Customers.xlsx")
types <- read_excel("Cookie Types.xlsx")

# 通过Product字段关联订单与产品数据
orders %>%
  left_join(types, by = "Product") %>%
  mutate(
    cost = `Cost Per Cookie` * `Units Sold`,
    rev = `Revenue Per Cookie` * `Units Sold`,
    prof = rev - cost
  ) %>%
  group_by(Product) %>%
  # 计算组内总利润与总营收的比值
  summarize(percent = (sum(prof) / sum(rev)) * 100)
  • 关键说明:
    • 使用left_join确保每个订单匹配到对应产品的成本、营收数据;
    • summarize中通过sum()汇总组内总利润和总营收,再计算利润率,最终每个Product只会生成一个百分比值,与你期望的结果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:50:27