瞄准现有方法或构建了一个函数,用于返回R中 vector 中彼此最接近的x值的索引。这是一个示例

a <- c(10,85,20,75,80,5,105)

# function definition

getIndex <- function(x, n) {
}

# with x: vector to test and n: number of closest value to detect

# desired function output : and index identifying x closest values in the vector x

ind <- c(0,1,0,1,1,0,0) # or a a logical F,T,F,T,T,F,F # here with n = 3 (looking for 3 closest values)`

最佳答案

这可以通过查找排序 vector 的每个i th和(i+n-1) th元素之间的最小差异来完成。最小的差异将为您提供最接近的n个数字。

这是使用基数R的方法-

getIndex <- function(x, n) {
  x_s <- sort(x)
  rolling_diff <- c(x_s[n:length(x_s)], rep(NA, n-1)) - x_s
  w <- which.min(rolling_diff)
  x %in% x_s[w:(w+n-1)]
}

getIndex(a, 3)
[1] FALSE  TRUE FALSE  TRUE  TRUE FALSE FALSE

基准-
set.seed(2)
x <- sample(1000, 100)
identical(getIndex_Shree(x, 3), getIndex_Ronak(x, 3))
# [1] TRUE
microbenchmark::microbenchmark(
  shree = getIndex_Shree(x, 3),
  ronak = getIndex_Ronak(x, 3),
  times = 10
)

Unit: microseconds
  expr        min          lq         mean      median         uq         max neval
 shree      81.64      85.838     134.3092     162.346     166.08     174.476    10
 ronak 3157301.98 3249876.496 3308635.5102 3316360.354 3369009.09 3423373.176    10

关于r - 查找R中数组中彼此最接近的x的索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57111339/

10-12 17:24