我想在R中创建二部网络。例如,如果你有一个两种类型的data.frame (只能跨物种交互,不能在物种内交互),并且每个物种都有一个特征值(例如,捕食者的嘴巴大小允许谁吃哪个猎物物种),我们如何基于物种的特征来模拟网络(即,两个物种只有在它们的特征值重叠的情况下才能相互作用)?
更新:这是我想要做的一个最小的例子。1)构建系统发育树;2)在系统发育树上模拟性状;3)基于物种特征值建立网络。
# packages
install.packages(c("ape","phytools"))
library(ape); library(phytools)
# Make phylogenetic trees
tree_predator <- rcoal(10)
tree_prey <- rcoal(10)
# Simulate traits on each tree
trait_predator <- fastBM(tree_predator)
trait_prey <- fastBM(tree_prey)
# Create network of predator and prey
## This is the part I can't do yet. I want to create bipartite networks, where
## predator and prey interact based on certain crriteria. For example, predator
## species A and prey species B only interact if their body size ratio is
## greater than X.
发布于 2012-08-28 09:42:02
答案的格式实际上取决于你下一步要做什么,但这里有一个尝试:
set.seed(101)
npred <- nprey <- 10
tree_predator <- rcoal(npred)
tree_prey <- rcoal(nprey)
## Simulate traits on each tree
trait_predator <- fastBM(tree_predator)
trait_prey <- fastBM(tree_prey)
(我使用set.seed(101)
来获得重现性,所以这些是我的特征结果...
> trait_predator
t1 t9 t4 t8 t5 t2
-2.30933392 -3.17387148 -0.01447305 -0.01293273 -0.25483749 1.87279355
t6 t10 t3 t7
0.70646610 0.79508740 0.05293099 0.00774235
> trait_prey
t10 t7 t9 t6 t8 t1
0.849256948 -0.790261142 0.305520218 -0.182596793 -0.033589511 -0.001545289
t4 t5 t3 t2
-0.312790794 0.475377720 -0.222128629 -0.095045954
...)
您所生成的值是在一个无界空间上生成的,因此采用它们的比率并没有实际意义;我们假设它们是大小的对数,因此exp(x-y)
将是捕食者/猎物大小的比率。随意地,我假设分界值是1.5...
使用outer
比较所有捕食者与猎物的特征:这将创建一个二进制(0/1)矩阵。
bmatrix <- outer(trait_predator,trait_prey,
function(x,y) as.numeric(exp(x-y)>1.5))
可视化结果的一种方法是...
library(Matrix)
image(Matrix(bmatrix),xlab="Prey",ylab="Predator",sub="")
例如,你可以看到捕食者#6 (在上面的输出中被标记为t2
)真的很大(对数size=1.87),所以它吃掉了所有的猎物物种……
使用igraph
(我这里的一些方法有点老生常谈)
library(igraph)
edges <- which(bmatrix==1,arr.ind=TRUE) ## extract vertex numbers
## distinguish prey (columns) from pred (rows)
edges[,2] <- npred+edges[,2]
gg <- graph.bipartite(rep(1:0,c(npred,nprey)),
c(t(edges)))
## c(t(edges)) collapses the two-column matrix to a vector in row order ...
## now plot ...
plot(gg,vertex.color=rep(c("cyan","pink"),c(npred,nprey)),
edge.arrow.mode=">")
这与上面的矩阵格式相匹配--捕食者1和2 (=顶点1和2)不吃任何人,猎物2(=顶点12)被许多不同的捕食者吃掉...这种表示更漂亮,但不一定更清楚(例如,捕食者7和8都吃猎物2(顶点12),但它们的箭头重合)。但是,如果您想要应用图论方法,那么将其转换为igraph
格式可能更好(并且有太多的布局选项可用于绘制图形)。
https://stackoverflow.com/questions/12150630
复制相似问题