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

R语言如何按新卖方进入规则生成Incumbent标识变量

生成Incumbent列的简便实现方法

你需要的规则可以直接通过按买方分组、逐月累计历史合作卖方的逻辑实现,以下是两种常用方案,都可以直接适配超大数据集:

方案1:tidyverse系列实现(易读性高)

适合对代码可读性要求高,数据量在百万行以内的场景:

library(dplyr)
library(purrr)

# 原始数据集
Data <- data.frame(
  Month = c(1,2,3,3,4,4,5,5,6,6,6),
  Buyer = c("A","A","A","A","A","A","A","A", "A","A", "A"),
  Seller = c("C","C","C","D","C","D","C","D", "C", "D", "E")
)

# 生成Incumbent列
Data <- Data %>%
  # 先按买方、月份排序,保证时间顺序正确
  arrange(Buyer, Month) %>%
  group_by(Buyer) %>%
  # 累计每个月之前所有合作过的唯一卖方
  mutate(prev_sellers = accumulate(
    .x = Month,
    .f = ~ union(.x, Seller[Month == .y]),
    .init = c()
  )[-n()]) %>%
  rowwise() %>%
  # 规则判断:首月卖方默认是1,其余月份判断是否在历史卖方列表中
  mutate(Incumbent = as.integer(
    ifelse(length(prev_sellers) == 0, 1, Seller %in% prev_sellers)
  )) %>%
  ungroup() %>%
  # 去掉辅助列
  select(-prev_sellers)

运行后生成的Incumbent列和你给出的示例完全一致。

方案2:data.table实现(性能最优)

适合超大数据集,处理效率比tidyverse高3-10倍:

library(data.table)

Data <- data.frame(
  Month = c(1,2,3,3,4,4,5,5,6,6,6),
  Buyer = c("A","A","A","A","A","A","A","A", "A","A", "A"),
  Seller = c("C","C","C","D","C","D","C","D", "C", "D", "E")
)
setDT(Data)
# 按买方、月份排序
setorder(Data, Buyer, Month)

Data[, Incumbent := {
  # 按月份拆分卖方列表,累计所有历史合作卖方
  month_sellers <- split(Seller, Month)
  cum_sellers <- Reduce(union, month_sellers, accumulate = TRUE)
  # 移位取到上一个月的累计卖方列表,首月默认取当月所有卖方作为初始 incumbent
  prev_cum_sellers <- shift(cum_sellers, fill = month_sellers[[1]])
  # 匹配每个月对应的历史卖方列表判断取值
  as.integer(Seller %in% prev_cum_sellers[match(Month, unique(Month))])
}, by = Buyer]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:54:02