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

按年度销售额筛选Top2产品并合并其余产品为“Other”的R代码实现需求

解决方案:R实现Top2产品提取+其他产品合并汇总

我来帮你搞定这个需求,直接上可运行的代码加详细解释:

步骤1:准备原始数据

先还原你的输入数据:

# 原始输入数据
Year <- c(2010,2010,2010,2010,2010,2011,2011,2011,2011,2011,2012,2012,2012,2012,2012)
Model <- c("a","b","c","d","e","a","b","c","d","e","a","b","c","d","e")
Sale <- c("30","45","23","33","24","11","56","19","45","56","33","32","89","33","12")
df <- data.frame(Year, Model, Sale)

步骤2:核心处理代码

我们使用dplyr和purrr包来高效处理数据(如果没安装的话先运行install.packages(c("dplyr", "purrr"))):

library(dplyr)
library(purrr)

# 1. 转换销售额类型:保留原始字符串用于拼接,同时转数值型计算总和
df <- df %>%
  mutate(Sale_num = as.numeric(Sale))

# 2. 计算各产品三年总销售额,筛选出Top2产品
top2_models <- df %>%
  group_by(Model) %>%
  summarise(total_sales = sum(Sale_num), .groups = "drop") %>%
  arrange(desc(total_sales)) %>%
  slice(1:2) %>%
  pull(Model)

# 3. 按年度分组处理:保留Top2产品,合并其他产品为"other"并展示计算过程
final_result <- df %>%
  group_by(Year) %>%
  group_split() %>%
  map_dfr(function(year_group) {
    # 提取当前年度的Top2产品记录
    top2_records <- year_group %>%
      filter(Model %in% top2_models) %>%
      select(Year, Model, Sale)
    
    # 处理其他产品:拼接销售额公式+计算总和
    other_records <- year_group %>%
      filter(!Model %in% top2_models) %>%
      summarise(
        Year = first(Year),
        Model = "other",
        Sale = paste0(paste(Sale, collapse = "+"), "=", sum(Sale_num))
      )
    
    # 合并当前年度的所有记录
    bind_rows(top2_records, other_records)
  })

# 查看最终结果
print(final_result, n = Inf)

代码解释

  1. 类型转换:因为原始Sale是字符型,我们新增Sale_num数值列用于计算总和,同时保留原始字符列用于拼接other的公式文本。
  2. 筛选Top2产品:按Model分组求和,降序排序后取前2个,得到的top2_models就是总销售额最高的两个产品(对应示例中的b和c)。
  3. 年度分组处理:把数据按年度拆分后逐个处理,每个年度内分别提取Top2产品的原始记录,再把其他产品的销售额拼接成X+Y+Z=总和的格式,最后合并两类记录。

运行结果

执行代码后会得到符合你要求的输出:

# A tibble: 9 × 3
   Year Model Sale          
  <dbl> <chr> <chr>         
1  2010 b     45            
2  2010 c     23            
3  2010 other 30+33+24=87   
4  2011 b     56            
5  2011 c     19            
6  2011 other 11+45+56=112  
7  2012 b     32            
8  2012 c     89            
9  2012 other 33+33+12=78   

注:你示例中2010年的other总和写的是92,实际30+33+24=87,代码会自动计算正确的数值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 18:42:36