R语言求和时如何选取which()返回的首个匹配元素避免报错
解决R语言中时间匹配多结果时的求和问题
问题根源
当team2_times的元素与race_times中多个时间的差值相等时,which()会返回多个索引,直接用于取数会一次获取多个score,不符合你想要取第一个匹配结果的需求;另外原代码中i <- 0:n会包含索引0,导致取到team2_times[0](NA值),这也是潜在问题。
解决方案
对每个team2_times元素,找到差值最小的第一个匹配项,再汇总求和,可通过sapply结合索引取第一个的方式实现:
修改后的完整代码
library(hms) # 需先加载hms包,as_hms依赖该包 team2_times <- as_hms(c('00:19:31', '00:20:01', '00:20:22','00:20:31', '00:21:00')) race_times <- data.frame( times = as_hms(c('00:19:19', '00:19:31', '00:19:32', '00:19:50', '00:20:35', '00:18:35', '00:19:59', '00:20:12', '00:20:14', '00:21:06', '00:17:31', '00:20:07', '00:20:30', '00:20:53', '00:21:13')), score = c(6, 12, 13, 15, 26, 2, 20, 41, 63, 94, 17, 47, 83, 121, 172) ) # 遍历每个team2_times元素,取第一个匹配的score matched_scores <- sapply(team2_times, function(t) { diffs <- abs(race_times$times - t) # 定位差值最小的第一个位置 first_match_idx <- which(diffs == min(diffs))[1] race_times$score[first_match_idx] }) # 计算总和 total_sum <- sum(matched_scores) print(total_sum)
关键修改点
- 用
sapply遍历team2_times的每个元素,避免手动索引出错; - 在
which(diffs == min(diffs))后添加[1],强制只取第一个匹配的索引; - 移除原代码中错误的
i <- 0:n,直接遍历向量元素更直观。
验证单个元素的情况
针对你提到的team2_times[3],单独测试逻辑:
t <- team2_times[3] diffs <- abs(race_times$times - t) which(diffs == min(diffs)) # 返回两个匹配索引 which(diffs == min(diffs))[1] # 仅保留第一个索引,对应score=63
内容的提问来源于stack exchange,提问作者Harry Murphy
相关产品推荐
相关产品推荐

