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
相关产品推荐
相关产品推荐

