假设我有一个如下形式的矩阵:
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被跳过。我想做的是在每个残基到其他残基之间建立一个“距离矩阵”。在这种情况下,我想做一个7x7的矩阵,元素(1,3)是这些位置之间的距离。
现在,我意识到我不需要填写下半部分,对角线以上的所有内容都足够了。我还看到了如何使用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语句(或者更聪明的语句)来生成这个矩阵?我试过这样做,但不知何故没有成功。谢谢你的帮助!
发布于 2012-08-15 07:03:38
您要查找的是dist函数。详情请参见?dist。
我不明白你期望一个7乘7的矩阵,然后让元素1,3引用它们之间的距离是什么意思(在注意到没有5,6,7之后)。我将其理解为您希望引用Can.Count。您可以通过命名行和列并引用这些名称来完成此操作。
假设您的数据是一个名为residues的data.frame,则可以使用以下方法
c('XCoord','YCoord')计算二维距离。通过使用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 boundshttps://stackoverflow.com/questions/11961653
复制相似问题