首页 > 解决方案 > 通过列表/向量中的索引选择最接近的 x 元素

问题描述

如果我有一个向量,例如x <-c(1,2,3,4,5,6,7,8,9),我想要一个函数 f , f(vector,index,num)它在哪里获取向量并num在索引上为我提供与该向量“最接近”的元素示例: f(x,3,4) = c(1,2,4,5) f(x,1,5) = c(2,3,4,5,6) f(x,8,3) = c(6,7,9)

由于还有一个问题,如果我们有一个奇数,我们需要选择是对称选择左侧还是右侧,让我们选择左侧(但右侧也可以)即f(x,4,5) = c(1,2,3,5,6) and f(x,7,3) = c(5,6,8)

我希望我的问题很清楚,感谢您的任何帮助/回复!

编辑: 的原始向量c(1:9)是任意的,该向量可以是字符串向量,也可以是长度为 1000 的向量,其中包含重复的随机数字等。

IEc(1,7,4,2,3,7,2,6,234,56,8)

标签: rvectorindicesclosest

解决方案


num_closest_by_indices <- function(v, idx, num) {
  # Try the base case, where idx is not within (num/2) of the edge
  i <- abs(seq_along(x) - idx)
  i[idx] <- +Inf # sentinel

  # If there are not enough elements in the base case, incrementally add more
  for (cutoff_idx in seq(floor(num/2), num)) {
    if (sum(i <= cutoff_idx) >= num) {
      # This will add two extra indices every iteration. Strictly if we have an even length, we should add the leftmost one first and `continue`, to break ties towards the left.
      return(v[i <= cutoff_idx])
    }
  }
} 

下面是这个算法的一个例子:我们按照期望的顺序对索引进行排序,然后选择最低num的合法索引:

> seq_along(x)
  1 2 3 4 5 6 7 8 9
> seq_along(x) - idx
  -2 -1  0  1  2  3  4  5  6
> i <- abs(seq_along(x) - idx)
   2  1  0  1  2  3  4  5  6
> i[idx] <- +Inf # sentinel to prevent us returning the element itself
   2   1 Inf   1   2   3   4   5   6

现在我们可以找到num具有最小值的元素(任意打破平局,除非您有偏好(左))。我们的第一个猜测是所有索引 <= (num/2) ;如果在开始/结束index之内,这可能还不够。(num/2)

> i <= 2
  TRUE  TRUE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE
> v[i <= 2]
  1 2 4 5

因此,调整@dash2 的代码来处理某些索引非法(非正数,或 > 长度(x))的极端情况,即! %in% 1:L. 然后min(elems)是我们无法选择的非法索引的数量,因此我们必须选择abs(min(elems))更多。

笔记:

  • 最后,代码通过三个分段案例处理起来更简单,更快捷。哇。
  • (num+1)如果我们选择索引,它实际上似乎简化了事情,然后idx在返回答案之前删除。用来result[-idx]删除它。

推荐阅读