【问题标题】:Finding vector positions for which values are close to the elements of another vector查找其值接近另一个向量的元素的向量位置
【发布时间】:2018-08-22 18:16:49
【问题描述】:

我想在一个向量中找到其值最接近另一个向量的位置(即索引)。例如:

v1 <- c(0, 0.25, 0.5, 0.75, 1, 1.25, 1.5)
v2 <- c(0.1, 0.33, 0.98)

我想找到一个向量,它包含 v1 的位置,其值与 v2 的元素一样接近,即:

# Desired output
v3 <- c(1, 2, 5) # since 0.1 is closest to 0, 0.33 is closest to 0.25, ...

【问题讨论】:

    标签: arrays r vector


    【解决方案1】:

    我找到了自己问题的答案。这是解决方案:

    v1 <- c(0, 0.25, 0.5, 0.75, 1, 1.25, 1.5)
    v2 <- c(0.1, 0.33, 0.98)
    

    我们将使用函数findInterval

    position <- findInterval(v2, v1) # result: c(1 2 4)
    

    问题是我们需要知道它是更接近上限还是下限。因此,我们创建一个新向量,将每个区间除以 2,并对向量进行排序:

    v1p <- sort(c(v1, v1 - (v1 - shift(v1))/2)) # result:  c(0.000 0.125 0.250 0.375 0.500 0.625 0.750 0.875 1.000 1.125 1.250 1.375 1.500)
    
    # Position in new vector
    position_new <- findInterval(v2, v1p)
    
    # Now if position is odd: lower bound, if position number is even: upper bound:
    is.even <- function(x) x %% 2 == 0
    final_position <- position + is.even(position_new)
    
    print(final_position)
    [1] 1 2 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-26
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 2020-12-29
      • 2021-08-03
      相关资源
      最近更新 更多