R语言 选择求和中列表的单个元素

blmhpbnm  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(123)

我正在尝试用R写一个summattaion,但是遇到了问题。下面是我的代码:

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))
n <- length(team2_times)
i <- 0:n
sum(race_times[which(abs(race_times$times - team2_times[i]) == min(abs(race_times$times - team2_times[i]))),2])

这对其他时间向量有效,但对这个向量无效。由于team2_times向量的第三个条目与两个值的距离相等,因此()返回两个值,并且求和无法计算:

sum(race_times[which(abs(race_times$times - team2_times[3]) == min(abs(race_times$times - team2_times[3]))),2])

有没有方法可以选择which()函数的第一个输出(在本例中为63),以便继续对值求和而不会出现此问题?
我试过其他功能,如sapply,但它没有工作。

cnjp1d6j

cnjp1d6j1#

您可能正在寻找which.min

race_times[which.min(abs(race_times$times - team2_times[3])), 2]
#> [1] 63

sapply(team2_times, function(x) race_times[which.min(abs(race_times$times - x)), 2])
#> [1] 12 20 63 83 94

sum(sapply(team2_times, function(x) race_times[which.min(abs(race_times$times - x)), 2]))
#> [1] 272

或者用data.table

library(data.table)

setDT(race_times)[data.table(times = team2_times), on = "times", roll = "nearest"]$score
#> [1] 12 20 63 83 94

sum(setDT(race_times)[data.table(times = team2_times), on = "times", roll = "nearest"]$score)
#> [1] 272

相关问题