[英]How to generate an individual adjacency matrix from a group adjacency matrix, in r
我有一個通過物種相互作用(三營養鏈)表示物種的鄰接矩陣:
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")))
和一個包含物種豐度的 dataframe:
comm = t(data.frame(sp1=100,
sp2=20,
sp3=5))
使用上述方法,是否有一種有效的方法來創建基於個體的鄰接矩陣?
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))))
因此 sp3 的所有個體都與 sp2 的所有個體以及 sp1 的所有個體相連。 我會很感激任何指示,我沒有設法找到類似的問題,也許是因為我沒有使用適當的術語。
為了說明,我們將在最后的注釋中使用一個較小的示例,但相同的代碼將適用於問題中的示例。 除非另有說明,否則不使用任何包裝。
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)使用上述 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)
也可以使用 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.