使用dplyr汇总多变量:按渠道统计商品销量与商品数量
问题解决:计算各渠道商品销售总量与唯一商品数
原始数据
Article Channel1_qty Channel2_qty Channel3_qty 110 30 10 0 110 40 0 10 111 50 5 2 111 60 3 18
期望结果
Article_count | channel | Sum (total article qty for channel) 2 1 180 2 2 18 2 3 30
原代码问题分析
你的代码存在两个关键问题:
group_by(channel)后缺少管道符%>%,无法衔接后续的summarise操作,属于语法错误。- 转长格式后
channel列的取值是channel1_qty这类字符串,需要提取数字部分作为渠道编号,才能匹配期望结果的格式。
修正后的代码
推荐使用tidyr的pivot_longer(替代已退役的gather),结合dplyr完成需求:
library(dplyr) library(tidyr) library(stringr) df %>% select(Article, starts_with("Channel")) %>% # 批量选择商品列和渠道销量列 pivot_longer( cols = -Article, names_to = "channel", values_to = "value" ) %>% mutate(channel = as.integer(str_extract(channel, "\\d+"))) %>% # 提取渠道编号 group_by(channel) %>% summarise( Article_count = n_distinct(Article), `Sum (total article qty for channel)` = sum(value) ) %>% ungroup() # 取消分组,避免后续操作受影响
代码说明
select(Article, starts_with("Channel")):用starts_with批量匹配渠道列,比逐个列名更简洁灵活。pivot_longer:将宽格式数据转为长格式,把多列渠道销量合并为channel(渠道标识)和value(销量值)两列。mutate(channel = ...):用str_extract提取channel字符串中的数字,转为整数类型,得到纯渠道编号。group_by(channel)+summarise:按渠道分组后,计算两个核心指标:Article_count:该渠道覆盖的唯一商品数量(n_distinct(Article))Sum (total article qty for channel):该渠道的累计销售总量(sum(value))
内容的提问来源于stack exchange,提问作者cigarettes_after_text
相关产品推荐
相关产品推荐

