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

如何在R的data.table中按自定义优先级去重及统计指定运动客户数?

解决方案

1. 按自定义优先级去重(保留每个customerID最高优先级记录)

假设你的data.table对象名为dt,通过定义优先级映射、排序分组的方式保留最高优先级记录:

步骤1:定义优先级映射

library(data.table)
# 匹配需求的优先级规则
color_prio <- c(green=3, red=2, blue=1)
sport_prio <- c(soccer=3, basketball=2, tennis=1)

步骤2:分组去重(按color优先,再按sport优先)

给每行添加优先级数值后,按customerID分组,降序排序后保留每组第一行:

# 新增优先级列(也可直接在排序时调用映射,无需新增列)
dt[, `:=`(color_rank = color_prio[color], sport_rank = sport_prio[sport])]

# 分组筛选最高优先级记录
dt_deduped <- dt[order(-color_rank, -sport_rank), .SD[1], by = customerID]

# 清理临时列(可选操作)
dt_deduped[, c("color_rank", "sport_rank") := NULL]

如果需要给color更高权重的综合优先级,可计算总分数后排序:

dt[, total_rank := color_prio[color] * 10 + sport_prio[sport]] # color权重放大10倍
dt_deduped <- dt[order(-total_rank), .SD[1], by = customerID]
dt_deduped[, total_rank := NULL]

2. 统计同时拥有soccer和basketball记录的客户数

通过分组筛选出同时包含两种运动的客户,再统计数量:

方法一:分步筛选

# 按客户分组,标记是否拥有目标运动
customer_sports <- dt[, .(
  has_soccer = "soccer" %in% sport,
  has_basketball = "basketball" %in% sport
), by = customerID]

# 统计同时满足的客户数量
target_count <- nrow(customer_sports[has_soccer & has_basketball])

方法二:链式高效操作

target_count <- dt[, .(unique_sports = unique(sport)), by = customerID][
  , sum(all(c("soccer", "basketball") %in% unique_sports))
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:30:54