R 在一个向量中查找其索引不存在于另一个向量中的元素

R to find elements in a vector that their indices dose not exist in another vector

我有一个像下面这样的向量:

VEC = c(4,8,8,8)

我还有一个索引向量,它告诉我应该忽略 VEC 中的哪些元素:

indx = c(2,4)

我想获取值为 8 的第一个元素的索引,但索引不存在于 indx 数组中。我该怎么做?

所以基本上我应该得到 3 作为答案。 VEC[3] = 8(但第二个8不是第一个)。


这是另一个 VEC = c(1,3,5,3,3,3,3) 这里是忽略列表:indx=c(1,2,4,6) 假设我正在寻找匹配 3 的值。应该是 return 的索引是 5,因为 VEC[1], VEC[2], VEC[4], VEC[6] 在忽略列表中并且第一次出现的索引值为 5。

如果你想要原始索引,那么你可以这样做

VEC <- c(4,8,8,8)
indx <- c(2,4)

which(VEC==8 & !(seq_along(VEC) %in% indx))
which(VEC==8 & !(seq_along(VEC) %in% indx))[1] #to get just the first

这有点难看,但可能更有效率

ok<-`[<-`(!logical(length(VEC)), indx, FALSE)
which(VEC==8 & ok)
which(VEC==8 & ok)[1] #to get just the first

这可能更有效

VEC <- c(4,8,8,8)
indx <- c(2,4)

VEC[indx] <- NA
which(VEC==8)[1]