gpt4 book ai didi

r - 将值匹配到 R 中另一个列表中最近的较大值

转载 作者:行者123 更新时间:2023-12-05 03:51:31 24 4
gpt4 key购买 nike

several questions关于如何从列表中找到最接近给定数字的数字。这些答案主要涉及 whichwhich.min 是双向的,因此它们从列表中返回最接近给定数字的数字,而不管它是否数字大于或小于给定数字。

我想强制返回的数字大于给定的数字,除非给定的数字本身出现在列表中。这个功能可以,但是有没有更简单的方法呢?

viable_numbers <- c(15, Inf, 5, 10, 5)

picker <- function(x, viable_numbers) {
if (x %in% viable_numbers) {
return(x)

} else {
viable_numbers <- sort(unique(viable_numbers))
return(viable_numbers[findInterval(x, viable_numbers) + 1])
}
}

picker(x = 1, viable_numbers = viable_numbers)
[1] 5 # works
picker(x = 5, viable_numbers = viable_numbers)
[1] 5 # works
picker(x = 6, viable_numbers = viable_numbers)
[1] 10 # also works
picker(x = 20, viable_numbers = viable_numbers)
[1] Inf # still working

我更喜欢 base 解决方案,但也对 tidyverse 答案持开放态度。

最佳答案

您可以取等于或大于 x 的可行数子集的最小值:

picker <-  function(x, viable_numbers) {
min(viable_numbers[viable_numbers >= x])
}

picker(x = 1, viable_numbers = viable_numbers)
[1] 5
picker(x = 5, viable_numbers = viable_numbers)
[1] 5
picker(x = 6, viable_numbers = viable_numbers)
[1] 10
picker(x = 20, viable_numbers = viable_numbers)
[1] Inf

关于r - 将值匹配到 R 中另一个列表中最近的较大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62834581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com