使用R dplyr筛选满足多条件的最优10人球员组合
优化实现方案
你原来的全量10人组合方案计算量过大,我们可以通过按角色拆分生成组合的方式大幅降低计算量,直接从生成环节就满足2C/4F/4G的配额要求,避免后续无效筛选,配合dplyr+purrr可以高效实现需求。
实现步骤
- 按角色拆分球员数据集,分别生成对应配额的位置组合
- 预计算每个位置组合的得分总和、index总和
- 交叉拼接所有位置组合,筛选总得分符合区间要求的结果
- 按总index降序排序,排在最前的就是你要的最优组合
完整代码
library(tidyverse) # 你提供的示例数据集 set.seed(123) players <- paste("player",rep(1:20)) score <- runif(20, min=4, max=16.7) index <- runif(20, min=-1, max=9) role <- rep(c("C","F","F","G","G"),4) df <- data.frame(players, score, index,role) # 自定义函数:生成指定位置、指定人数的所有组合,返回组合的球员列表、得分和、index和 gen_role_combs <- function(data, role_name, pick_n) { combn(nrow(data), pick_n, simplify = FALSE) %>% map_dfr(~{ selected <- slice(data, .x) tibble( !!sym(paste0(role_name, "_players")) := list(selected$players), !!sym(paste0(role_name, "_score")) := sum(selected$score), !!sym(paste0(role_name, "_index")) := sum(selected$index) ) }) } # 按角色拆分数据集 c_df <- filter(df, role == "C") f_df <- filter(df, role == "F") g_df <- filter(df, role == "G") # 生成各位置符合配额的组合 c_combs <- gen_role_combs(c_df, "C", 2) f_combs <- gen_role_combs(f_df, "F", 4) g_combs <- gen_role_combs(g_df, "G", 4) # 拼接所有组合,筛选符合得分要求的结果,按总index降序排序得到最优组合 result <- crossing(c_combs, f_combs, g_combs) %>% mutate(total_score = C_score + F_score + G_score, total_index = C_index + F_index + G_index) %>% filter(total_score >= 95.5, total_score <= 100.4) %>% arrange(desc(total_index)) # 提取最优组合的10名球员名单 best_10_players <- c(result$C_players[[1]], result$F_players[[1]], result$G_players[[1]]) best_10_players
效果说明
该方案的总计算量仅为C(4,2)*C(8,4)*C(8,4)=29400次,对比你原来全量10人组合的C(20,10)=184756次,计算量降低84%,运行效率提升非常明显。
内容的提问来源于stack exchange,提问作者LDT
相关产品推荐
相关产品推荐

