Reputation: 55
I have a large matrix that is composed of 0s and 1s. I would like to find the distance between 1s.
For example, if I have the first row of a matrix as
0 0 1 0 1 1 0
I want the output
3 2 1
3 is the location of the first 1 2 is the distance between the first and second 1 1 is the location of the second and the third 1
How do I accomplish this?
Upvotes: 2
Views: 54
Reputation: 886948
One option is which
with diff
. Convert the vector
to logical, find the index where the values are 1 with which
and get the diff
erence of index positions
i1 <- which(as.logical(v1))
out <- c(i1[1], diff(i1))
out
#[1] 3 2 1
v1 <- c(0, 0, 1, 0, 1, 1, 0)
Upvotes: 2