Oui*_*iti 1 size loops r sample
我是R的新用户,我试图编写一个用于模拟物种入侵和社区稳定性的脚本.我几乎完成了它,我在循环中只有一个小问题.
我有40种(1,2,......)的池,我通过连续入侵创建了一个社区.社区中的物种会离开入侵者池,除非它们灭绝(我设置了密度阈值).
我想要很多入侵(> 4000)所以我创建了一个4000到1到40之间的数字(random.order),但我有一个问题,因为我的物种密度矩阵(init.x)的数量不同元素作为我的向量.
time<- list(start=0,end=4000,steps=100)
# Initial conditions (set all species to zero in the beginning)
init.x <- runif(n)*0
# generate random order in which species are introduced
init.order<- sample(1:n)
order<-rep(order,100)
random.order<-sample(order,size=length(order))
outt <- init.x
**for (i in 1:4000){
# Introduce 1 new species (according to vector "random.order") with freq 1000*tol
# if the species is not yet in the init.x matrix
if (init.x[random.order[i]]<tol) {init.x[random.order[i]] <- 1000*tol}**
# integrate lvm model
out <-n.integrate(time=time,init.x=init.x,model=lvm)
# save out and attach it to outt
outt <- rbind(outt,out)
# generate new time window to continue integration
time <- list(start=time$end, end = time$end+time$end-time$start,
steps=100)
}
Run Code Online (Sandbox Code Playgroud)
我知道这可能很简单,但是我找不到一种方法来编写我的循环以获得比物种数量更多的入侵(我的矩阵中的原始数量).
非常感谢,
你可能想改变
# Initial conditions (set all species to zero in the beginning)
init.x <- runif(n)*0
# generate random order in which species are introduced
init.order<- sample(1:n)
order<-rep(order,100)
random.order<-sample(order,size=length(order))
Run Code Online (Sandbox Code Playgroud)
成
# Initial conditions (set all species to zero in the beginning)
init.x <- rep.int(0, n) #should be a lot faster
# generate random order in which species are introduced
random.order<-sample.int(n,size=4000, replace=TRUE)
Run Code Online (Sandbox Code Playgroud)
...解决您的主要问题(检查?样本).我没有检查你们其余的代码,但可能还有更多优化空间.