Louis
Louis

Reputation: 55

How do I find the distance between two points in a matrix of sequences?

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

Answers (1)

akrun
akrun

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 difference of index positions

i1 <- which(as.logical(v1))
out <- c(i1[1], diff(i1))
out
#[1] 3 2 1

data

v1 <- c(0, 0, 1, 0, 1, 1, 0)

Upvotes: 2

Related Questions