R:查找另一个向量中向量的索引(如果存在)

2024-04-26

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

我想寻找什么重要的东西exactly相同的向量。因此,对于c(1, 1) inside c(1, 0, 1, 1, 1, 0)这是假的c(1, 1) != c(1, 1, 1).

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

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

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


这个函数应该可以工作:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R:查找另一个向量中向量的索引(如果存在) 的相关文章

随机推荐