将值匹配到 R 中另一个列表中最近的较大值
Match values to nearest, larger value in another list in R
有 several 关于如何从列表中找到最接近给定数字的数字。这些答案主要涉及 which
或 which.min
是双向的,因此它们 return 列表中最接近给定数字的数字,无论该数字是否更大或小于给定的数字。
我想强制 returned 数字大于给定数字,除非给定数字本身出现在列表中。这个功能可以用,但是有没有更简单的方法呢?
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
有 several which
或 which.min
是双向的,因此它们 return 列表中最接近给定数字的数字,无论该数字是否更大或小于给定的数字。
我想强制 returned 数字大于给定数字,除非给定数字本身出现在列表中。这个功能可以用,但是有没有更简单的方法呢?
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