[英]How to generate an individual adjacency matrix from a group adjacency matrix, in r
I have an adjacency matrix representing species by species interactions (a tri-trophic chain):我有一个通过物种相互作用(三营养链)表示物种的邻接矩阵:
mat = matrix(c(0,1,0,
0,0,1,
0,0,0), nrow=3, byrow = T,
dimnames = list(c("sp1","sp2","sp3"),
c("sp1","sp2","sp3")))
and a dataframe that contains the species' abundances:和一个包含物种丰度的 dataframe:
comm = t(data.frame(sp1=100,
sp2=20,
sp3=5))
Using the above, is there an efficient way to create an individual based adjacency matrix?使用上述方法,是否有一种有效的方法来创建基于个体的邻接矩阵?
in.mat = matrix(0, nrow = sum(comm),
ncol = sum(comm),
byrow = T,
dimnames = list(c(rep("sp1",100),rep("sp2",20),rep("sp3",5)),
c(rep("sp1",100),rep("sp2",20),rep("sp3",5))))
So that all individuals of sp3 are connected with all individuals from sp2 and those with all individuals of sp1.因此 sp3 的所有个体都与 sp2 的所有个体以及 sp1 的所有个体相连。 I would appreciate any pointers, I have not managed to find similar questions, perhaps because I am not using the appropriate terms.
我会很感激任何指示,我没有设法找到类似的问题,也许是因为我没有使用适当的术语。
To illustrate we will use a smaller example shown in the Note at the end but the same code would work with the example in the question.为了说明,我们将在最后的注释中使用一个较小的示例,但相同的代码将适用于问题中的示例。 No packages are used except as indicated.
除非另有说明,否则不使用任何包装。
1) Expand the names into nms and then use subscripting. 1)将名称展开为 nms,然后使用下标。
nms <- rep(rownames(comm), comm)
mat[nms, nms]
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
## [1,] 0 0 1 1 1 0 0 0 0
## [2,] 0 0 1 1 1 0 0 0 0
## [3,] 0 0 0 0 0 1 1 1 1
## [4,] 0 0 0 0 0 1 1 1 1
## [5,] 0 0 0 0 0 1 1 1 1
## [6,] 0 0 0 0 0 0 0 0 0
## [7,] 0 0 0 0 0 0 0 0 0
## [8,] 0 0 0 0 0 0 0 0 0
## [9,] 0 0 0 0 0 0 0 0 0
2) Another approach using nms as above is to use one of these: 2)使用上述 nms 的另一种方法是使用以下方法之一:
outer(nms, nms, function(x, y) mat[cbind(x, y)])
outer(nms, nms, Vectorize(function(x, y) mat[x, y]))
sapply(nms, function(y) sapply(nms, function(x) mat[x, y]))
library(listcompr)
gen.matrix(mat[x, y], x = nms, y = nms)
The eList or comprehenr packages could also be used.也可以使用 eList 或 comprehenr 包。
# input
sp <- paste0("sp", 1:3)
mat <- matrix(c(0,0,0,1,0,0,0,1,0), 3, dimnames = list(sp, sp))
comm <- matrix(2:4, 3, dimnames = list(sp, NULL))
mat
## sp1 sp2 sp3
## sp1 0 1 0
## sp2 0 0 1
## sp3 0 0 0
comm
## [,1]
## sp1 2
## sp2 3
## sp3 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.