1

次の形式の行列があるとします。

Residue Can.Count SideChain XCoord  YCoord ZCoord
1       MET         1         A 62.935  97.579 30.223
2       THR         2         A 63.155  95.525 27.079
3       GLU         3         A 65.289  96.895 24.308
4       TYR         4         A 64.899  96.220 20.615
8       LYS         8         A 67.593  96.715 18.023
9       LEU         9         A 65.898  97.863 14.816
10       VAL        10         A 67.664  98.557 11.533

5〜6〜7の数字はスキップされていることに注意してください。私がやりたいのは、各残基と他の残基の間に「距離行列」を作成することです。この場合、要素(1,3)がそれらの位置の間の距離である7x7行列を作成したいと思います。

今、私は下半分を埋める必要がないことに気づきました。対角線より上のすべてで十分です。また、次のように2つのforループを使用してこれを行う方法もわかります。

 for(i in 1:7) {
  for(j in i:7){
    mymatrix[i,j] <- calcdistance(xyz1,xyz2) #I have the distance function already coded.

 }
}

常にO(n ^ 2)になることはわかっていますが、Rの力を利用して、applyステートメント(またはさらに賢いもの)を使用してこの行列を作成できるかどうか疑問に思っています。私はそうしようとしましたが、どういうわけか失敗しました。ヘップありがとうございます!

4

1 に答える 1

4

あなたが探しているのはdist機能です。詳細?distはをご覧ください。

7 x 7の行列を期待し、要素[1,3]がそれらの間の距離を参照することで何を意味するのかわかりません(5,6,7がないことに注意した後)。私はあなたが参照したいという意味でそれを取っていますCan.Count。これを行うには、行と列に名前を付け、これらの名前を参照します。

データがと呼ばれるdata.frameであるとするとresidues、次のように機能します

  • これは、xy座標を使用して2次元距離を計算することに注意してください c('XCoord','YCoord')。を使用すると、この3Dを簡単に作成できます c('XCoord','YCoord', 'ZCoord')

dist_matrix <-  as.matrix(dist(residues[, c('XCoord','YCoord')], diag = T))
# this gives a 7 by 7 matrix
dist_matrix
##         1        2         3         4        5        6        7
## 1 0.000000 2.065748 2.4513613 2.3883419 4.737453 2.976579 4.829071
## 2 2.065748 0.000000 2.5359132 1.8773814 4.594774 3.604205 5.433609
## 3 2.451361 2.535913 0.0000000 0.7795672 2.311021 1.143637 2.898770
## 4 2.388342 1.877381 0.7795672 0.0000000 2.739099 1.922875 3.620331
## 5 4.737453 4.594774 2.3110206 2.7390986 0.000000 2.047176 1.843368
## 6 2.976579 3.604205 1.1436367 1.9228755 2.047176 0.000000 1.897470
## 7 4.829071 5.433609 2.8987703 3.6203306 1.843368 1.897470 0.000000

# set the dimension names to the Can.Count so we can refer to them
dimnames(dist_matrix) <- list(residues[['Can.Count']],residues[['Can.Count']] )

# now you can refer to the distance between Can.Count 1 and Can.Count 8
dist_matrix['1','8']

## [1] 4.737453

# note that you need to refer to the dimension names as characters, 
# as this is  7 by 7 matrix, so the following will give 
# an (obvious) error message
dist_matrix[1,8]

## Error: subscript out of bounds
于 2012-08-14T23:03:37.917 に答える