简体   繁体   English

遍历“ dist”矩阵

[英]Loop through “dist” matrix

Let's first create dist object: 首先创建dist对象:

data(iris)
X <- iris[1:10, -5]
D <- dist(X)

I wonder how to iterate through rows / columns of dist object (eg, compute sum of the rows)? 我想知道如何遍历dist对象的行/列(例如,计算行的总和)?

We can convert the dist matrix to matrix by wrapping with as.matrix . 我们可以通过用as.matrix包装将dist矩阵转换为matrix This will give a symmetric matrix will diagonals as 0. As we need only either the lower or upper triangular values, we can assign one of them to '0' and do the rowSums 这将得到一个对称矩阵,对角线将为0。由于我们只需要上下三角值,我们可以将其中之一分配为'0'并进行rowSums

m1 <- as.matrix(D)
m1[upper.tri(m1, diag=TRUE)] <- 0
rowSums(m1)
colSums(m1)

Or we multiply ( * ) 'm1' with the logical index from the numeric row and col index of the matrix 'm1'. 或者我们将( * )'m1'乘以数字row的逻辑索引和矩阵'm1'的col索引。 The TRUE/FALSE values from the logical matrix will be transformed to 1/0 and when we multiply, values in 'm1' that correspond to '0' values will become 0 and others stay the same. 逻辑矩阵中的TRUE/FALSE值将转换为1/0 ,当我们相乘时,对应于“ 0”值的“ m1”中的值将变为0,而其他值保持不变。

rowSums(m1*(row(m1)>col(m1)))

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

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