Rstudio中跨两个不同表对网球球员胜负场对应列求和问题
原代码错误原因
- 循环逻辑错误:每次迭代都会覆盖
num_match_l$b整列的数值,最终结果仅和最后一次循环的i值相关,前面的迭代全部无效 - 取值不匹配:匹配到对应球员时直接返回
num_match_w$n整个向量,没有定位到该球员对应的获胜场次数值,维度不匹配导致结果错误
推荐解决方案
方案1:合并表计算(性能最优,逻辑清晰)
优先用R的表合并操作处理这类匹配需求,不需要写循环:
# 重命名列名统一球员标识 num_match_w_adj <- setNames(num_match_w, c("player", "win_count")) num_match_l_adj <- setNames(num_match_l, c("player", "lose_count")) # 若需要保留落败表全部384行,仅新增j列,用左连接 merge_res <- merge(num_match_l_adj, num_match_w_adj, by = "player", all.x = TRUE) # 若需要保留所有出现过的球员(含只出现在获胜表的球员),用全连接 # merge_res <- merge(num_match_l_adj, num_match_w_adj, by = "player", all = TRUE) # 计算总场次j,NA自动替换为0 merge_res$j <- rowSums(merge_res[, c("win_count", "lose_count")], na.rm = TRUE)
方案2:向量化遍历(不修改原表结构)
如果不想调整原表结构,用sapply遍历匹配即可,不需要写for循环:
num_match_l$j <- num_match_l$n + sapply(num_match_l$Loser, function(x) { ifelse(x %in% num_match_w$Winner, num_match_w$n[num_match_w$Winner == x], 0) })
参考表预览


内容的提问来源于stack exchange,提问作者Haroune Aaffoute
相关产品推荐
相关产品推荐

