Skip to content

Instantly share code, notes, and snippets.

@Rekyt
Last active January 21, 2016 12:50
Show Gist options
  • Select an option

  • Save Rekyt/54589c2a528fae53d571 to your computer and use it in GitHub Desktop.

Select an option

Save Rekyt/54589c2a528fae53d571 to your computer and use it in GitHub Desktop.
Matrix Indices Computation
# 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