简体   繁体   English

R比较特征以创建距离矩阵

[英]R comparing features to create matrix of distances

I have an R Question. 我有一个R问题。 I have an algorithm in mind which does this, but was wondering if there are neater ways of doing the following: 我有一个算法可以做到这一点,但我想知道是否有更巧妙的方法可以做到以下几点:

Say you have the following matrix: 假设您具有以下矩阵:

        [,1] [,2] [,3] [,4] [,5]
[A,]    0    0    0    0    1
[B,]    0    0    0    1    1
[C,]    0    0    1    1    1
[D,]    0    0    1    1    0
[E,]    1    0    0    0    0
[F,]    1    1    1    0    0

Now I want to create another matrix of the differences of each row to another row (ie, matrix of distances) something like (although I have it half filled, it is just mirror to get top part): 现在,我想创建另一行,将每一行与另一行之间的差异矩阵(即距离矩阵)类似(尽管我将其填充一半,但它只是获得顶部的镜像):

       [,A] [,B] [,C] [,D] [,E] [,F]
[A,]    0     
[B,]    1    0     
[C,]    2    1    0     
[D,]    3    2    1    0    
[E,]    2    3    4    3    0
[F,]    4    5    4    3    2    0

My method is to use a loop comparing each row's columns with corresponding columns of rows below, but with large matrices its not efficient. 我的方法是使用一个循环,将每一行的列与下面的行的相应列进行比较,但是使用较大的矩阵效率不高。 Any ideas on how to do this better? 关于如何做得更好的任何想法?

thx 谢谢

As said in the comment using dist with manhattan method: 如在使用distmanhattan方法的评论中所说:

dt <- read.table(text='     [,1] [,2] [,3] [,4] [,5]
[A,]    0    0    0    0    1
[B,]    0    0    0    1    1
[C,]    0    0    1    1    1
[D,]    0    0    1    1    0
[E,]    1    0    0    0    0
[F,]    1    1    1    0    0')

mm <- as.matrix(dt)
dist(mm,method='manhattan' ,diag=TRUE)

      [A,] [B,] [C,] [D,] [E,] [F,]
[A,]    0                         
[B,]    1    0                    
[C,]    2    1    0               
[D,]    3    2    1    0          
[E,]    2    3    4    3    0     
[F,]    4    5    4    3    2    0

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

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