简体   繁体   中英

R comparing features to create matrix of distances

I have an R Question. 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:

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

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