This is pretty direct to do if you use the "reshape2" package:
library(reshape2)
allMat <- do.call(rbind, lapply(l.mat, melt))
dcast(allMat, X1 ~ X2, fun.aggregate=sum)
# X1 sp1 sp2 sp3 sp4 sp5 sp6
# 1 h1 5 0 7 10 25 6
# 2 h2 16 2 2 3 2 3
Or, now that I think of it (since there's a melt
method for list
s, you can just do:
dcast(melt(l.mat), X1 ~ X2, value.var="value", fun.aggregate=sum)
If you want to stick with base R, I haven't found anything quite as direct. Here are two ways I came up with that's along the same lines as above:
Base option 1
allMat <- do.call(rbind, lapply(l.mat, function(x)
cbind(id = rownames(x), stack(data.frame(x)))))
xtabs(values ~ id + ind, data = allMat)
# ind
# id sp1 sp2 sp3 sp4 sp5 sp6
# h1 5 0 7 10 25 6
# h2 16 2 2 3 2 3
Base option 2
allMat <- do.call(rbind, lapply(l.mat, function(x) {
cbind(expand.grid(dimnames(x)), value = as.vector(x))
}))
allMat
xtabs(value ~ Var1 + Var2, allMat)
# Var2
# Var1 sp1 sp2 sp3 sp4 sp5 sp6
# h1 5 0 7 10 25 6
# h2 16 2 2 3 2 3