简体   繁体   中英

How to calculate distance between two integers in a matrix - R?

I have a matrix of 0's and 1's, (100 x 100). Not every row has a 1, some rows consist of just 0's.

I am trying to calculate the distance between the top most and bottom most value of 1 in the matrix. I am quite new to R (only learning about 3 weeks now). I tried using the dist() function but I am struggling to find out how to find the first row with a 1 and the last row with a 1 ends. Thanks for any help

Starting with Gregor's matrix, there are 1's in the first and last rows so the distance is 4 - 1 = 3:

M <- matrix(c(1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0), 4)
Mrows <- M * row(M)        # Identify rows with 1's
rownos <- Mrows[Mrows > 0] # Extract row numbers with 1's
(range(rownos))            # First and last rows with 1's
# [1] 1 4
(diff(range(rownos)))  # Difference between the last row and the first row
# [1] 3

If this is not what you want, you will have to provide more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM