首页 > 解决方案 > R:在另一个向量中查找向量的索引(如果存在)

问题描述

我想知道一个向量在另一个向量中的起始索引。例如,forc(1, 1)c(1, 0, 0, 1, 1, 0, 1)它将是 4。

重要的是我想寻找完全相同的向量。因此,对于c(1, 1)insidec(1, 0, 1, 1, 1, 0)它是 FALSE as c(1, 1) != c(1, 1, 1)

现在我正在检查短向量是否包含在长中,如下所示:

any(with(rle(longVec), lengths[as.logical(values)]) == length(shortVec)

但我不知道如何确定它的索引......

标签: r

解决方案


此功能应该起作用:

my_function <- function(x, find) {
  # we create two matrix from rle function
  m = matrix(unlist(rle(x)), nrow=2, byrow = T) 
  n = matrix(unlist(rle(find)), nrow=2, byrow = T)

  # for each column in m we see if its equal to n
  temp_bool = apply(m, 2, function(x) x == n) # this gives a matrix of T/F
  # then we simply sum by columns, if we have at least a 2 it means that we found (1,1) at least once
  temp_bool = apply(temp_bool, 2, sum)

  # updated part
  if (any(temp_bool==2)) {
    return(position = which(temp_bool==2)+1)
  } else {
    return(position = FALSE)
  }

}


my_function(x, find)
#[1] 4

my_function(y, find)
#[1] FALSE

为了在这里更清楚,我展示了这两个的结果apply

apply(m, 2, function(x) x == n)
#       [,1]  [,2] [,3]  [,4]  [,5]
# [1,] FALSE  TRUE TRUE FALSE FALSE
# [2,]  TRUE FALSE TRUE FALSE  TRUE  # TRUE-TRUE on column 3 is what we seek

apply(temp_bool, 2, sum)
#[1] 1 1 2 0 1

示例数据:

x <- c(1,0,0,1,1,0,1)
y <-  c(1,0,1,1,1,0)
find <- c(1,1) # as pointed this needs to be a pair of the same number

推荐阅读