Carleton Jack Carleton Jack - 1 month ago 8
R Question

In R how do I get the position for each element of a vector

for example, I have a sequence:

seq = sample(c(0,1), 11, replace = T)
1 0 0 0 1 1 1 1 1 1 0


the output gonna be:

1,2,5,11

Answer

Try this:

vec <- c(1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0)
c(1, which(diff(vec)!=0)+1)
#[1]  1  2  5 11

Checking whether diff() is different from zero is used to detect a change in the sequence. The index where the change occurs is retrieved with which(). The concatenation of the result with a leading 1 and the shifting of the index numbers by +1 is done because diff() reduces the length of the vector by one and the desired output contains 1 as the first index.