Is there a way to find a single occurence of a digit in a vector and ignore duplicates in R?

Viewed 70

I have an array of numbers and I'd like to find the index of a specific digit ONLY when it's occuring alone, NOT when it's occuring in a sequence of the same digit. For example:

a <- c(1,2,4,5,5,8,1,2,8,8,8,4,3)

I would like to find the index of the SINGLE 8 occuring at index 6, I'm not interested in any of the other digits, nor in the sequence of 8's occuring at index 9-11. Is there a clever way to do this in R?

1 Answers

An option would be rle. Apply the rle on the vector, create a logical index based on the values and lengths, and then wrap with which on the replicated logical vector

which(with(rle(a), rep(values == 8 & lengths == 1, lengths)))
#[1] 6
Related