Reputation: 350
I have a vector like the following:
VEC = c(4,8,8,8)
I also have an indices vector which tells me what elements in VEC
I should ignore:
indx = c(2,4)
I want to get the index of the first element whos value is 8
but the index does not exist in indx array. how can I do that?
So basically i should get 3
as the answer. VEC[3] = 8
(but the second 8 not the first one).
Here is another one
VEC = c(1,3,5,3,3,3,3)
and here is the ignore list: indx=c(1,2,4,6)
Let's say I'm looking for values that match 3. The index that should be return is 5 because VEC[1], VEC[2], VEC[4], VEC[6]
are in the ignore list and the first occurrence has index value of 5.
Upvotes: 0
Views: 718
Reputation: 6238
That might be more efficient
VEC <- c(4,8,8,8)
indx <- c(2,4)
VEC[indx] <- NA
which(VEC==8)[1]
Upvotes: 3
Reputation: 206177
If you want the original index, then you can do something like
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
This is a bit ugly but might be more efficient
ok<-`[<-`(!logical(length(VEC)), indx, FALSE)
which(VEC==8 & ok)
which(VEC==8 & ok)[1] #to get just the first
Upvotes: 4