Edit:
It now seems you are trying to sum the contents of columns, where those columns are greater than zero. This is confusing, because the first part of your question no longer applies (0 = absent, 1 = present). Hence, I have left your original data and the solution to the original problem down below. If you clarify what it is exactly you want, I can clear up the answer as well.
The matrix you now have in your question could be obtained as follows:
M <- structure(c(0.5, 0.3, 0.25, 0.5, 0.3, 0.25, 0, 0.3, 0.25, 0, 0, 0.25), .Dim = 3:4,
.Dimnames = list(c("Species1", "Species2", "Species3"),
c("AreaA", "AreaB", "AreaC", "AreaD")))
Shared <- matrix(0, nrow = ncol(M), ncol = ncol(M))
rownames(Shared) <- colnames(M)
colnames(Shared) <- colnames(M)
for(i in 1:ncol(M)){
Shared[i, -i] <- apply(M[, -i], 2, function(x){sum(pmin(M[, i] + x)[M[, i] > 0 & x > 0])})
}
> print(Shared)
AreaA AreaB AreaC AreaD
AreaA 0.0 2.1 1.1 0.5
AreaB 2.1 0.0 1.1 0.5
AreaC 1.1 1.1 0.0 0.5
AreaD 0.5 0.5 0.5 0.0
Old Answer
This solution sums the number of present species among areas:
M <- matrix(c(1,1,0,0,
1,1,0,0,
0,0,1,1), nrow = 3, byrow = TRUE)
colnames(M) <- paste0("Area", LETTERS[1:4])
rownames(M) <- paste0("Species", 1:3)
Shared <- matrix(0, nrow = ncol(M), ncol = ncol(M))
rownames(Shared) <- colnames(M)
colnames(Shared) <- colnames(M)
for(i in 1:ncol(M)){
Shared[i, -i] <- apply(M[, -i], 2, function(x){sum(M[, i] == 1 & x == 1)})
}
If you only want to display the upper triangular, simply do this:
Shared[lower.tri(Shared)] <- '' # or NA if you want the numbers to stay numbers
print(Shared)
> print(Shared)
AreaA AreaB AreaC AreaD
AreaA "0" "2" "0" "0"
AreaB "" "0" "0" "0"
AreaC "" "" "0" "1"
AreaD "" "" "" "0"
If you're just trying to find areas with larger overlap, you can also simply use a distance function instead (e.g. dist(t(M), method = "manhattan")
).