Last active
January 21, 2016 12:50
-
-
Save Rekyt/54589c2a528fae53d571 to your computer and use it in GitHub Desktop.
Matrix Indices Computation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Matrix of presence-absence | |
| m = structure(c(1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1), .Dim = c(4L, | |
| 4L), .Dimnames = list(c("a", "b", "c", "d"), c("site1", "site2", | |
| "site3", "site4"))) | |
| # Distance matrix | |
| dist = structure(c(0, 0.2, 0.7, 0.33, 0.2, 0, 0.5, 0.15, 0.7, 0.5, 0, | |
| 0.23, 0.33, 0.15, 0.23, 0), .Dim = c(4L, 4L), .Dimnames = list( | |
| c("a", "b", "c", "d"), c("a", "b", "c", "d"))) | |
| di_mat = do.call(cbind, | |
| tapply(m, col(m), function(x) { | |
| # 'x' is a column vector of m | |
| # Select sub distance matrix | |
| sub_dist = dist[which(x != 0), which(x != 0)] | |
| # sums all distances for all species | |
| di = colSums(sub_dist) | |
| di = di/(length(di) -1) | |
| # Returns given vector value if non zero | |
| ifelse(x != 0, di, x) | |
| }) | |
| ) | |
| # Copy dimensions names | |
| dimnames(di_mat) = dimnames(m) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment