简体   繁体   English

如何计算矩阵中两个整数之间的距离 - R?

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

I have a matrix of 0's and 1's, (100 x 100).我有一个 0 和 1 的矩阵(100 x 100)。 Not every row has a 1, some rows consist of just 0's.不是每一行都有 1,有些行只包含 0。

I am trying to calculate the distance between the top most and bottom most value of 1 in the matrix.我正在尝试计算矩阵中最高值和最低值 1 之间的距离。 I am quite new to R (only learning about 3 weeks now).我对 R 很陌生(现在只学习了大约 3 周)。 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.我尝试使用 dist() function 但我正在努力找出如何找到带有 1 的第一行和带有 1 的最后一行。 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:从 Gregor 矩阵开始,第一行和最后一行都有 1,因此距离为 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.如果这不是您想要的,您将必须提供更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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