1

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 (i.e., 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

4

1 回答 1

2

正如评论中所说,使用distwithmanhattan方法:

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
于 2013-09-23T19:36:58.677 回答