Reputation: 11676
Suppose I have a matrix of the following form:
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
Notice that the numbers 5-6-7 are skipped. What I want to do is make a "distance matrix" between each residue to each other residue. In this case, I want to make a 7x7 matrix with with element (1,3) being the distance between those positions.
Now, I realize that I don't need to fill in the bottom half, everything above the diagonal is sufficient. I also see how I could do this using 2 for loops as follows:
for(i in 1:7) {
for(j in i:7){
mymatrix[i,j] <- calcdistance(xyz1,xyz2) #I have the distance function already coded.
}
}
I realize that it will always be O(n^2) but I am wondering if I can leverage the power of R to make this matrix using an apply statement (or something even more clever)? I have tried doing so but have been unsuccessful somehow. Thank you for your hep!
Upvotes: 1
Views: 371
Reputation: 115382
What you are looking for is the dist
function. See ?dist
for details.
I'm not clear what you mean by expecting a 7 by 7 matrix, and then for the element [1,3]
to refer to the distance between those (after noting there is no 5,6,7). I am taking it to mean you wish to refer to the Can.Count
. You can do this by naming the rows and columns and referring to these names.
Assuming your data is a data.frame called residues
, the following will work
c('XCoord','YCoord')
. You could easily make this 3-D by using
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
Upvotes: 4