我有一个R问题。我有一个算法考虑到了这一点,但是想知道是否有更简洁的方法来执行以下操作:
假设你有以下矩阵:
[,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
现在我想创建另一个矩阵,每行与另一行的差异(即距离矩阵)之类的东西(虽然我有一半填充,它只是镜像得到顶部):
[,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
我的方法是使用一个循环来比较每一行的列和下面相应的行列,但是使用大矩阵它效率不高。关于如何做得更好的任何想法?
THX
答案 0 :(得分:2)
正如使用dist
manhattan
方法的评论所述:
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