如何将这两行代码重复100多次以上?

时间:2019-01-30 15:16:18

标签: r function model

我对编程世界还是一个陌生的人,正在为我随着时间的推移动物个体生长而建立的模型寻求指导。 我正在使用的代码的目标是 i)根据给定的分布生成随机的动物初始大小 ii)从给定的分布中给每个人一个开始的增长率 iii)计算1年后的个人新人数 iv)根据上述分配分配新的增长率 v)计算下一年的个人新人数。

到目前为止,我有下面的代码,我要做的是重复最后两行代码x次数,而不必一遍又一遍地物理运行代码。

# Generate starting lengths
lengths <- seq(from=4.4, to=5.4, by =0.1)

# Generate starting ks (growth rate)
ks <- seq(from=0.0358, to=0.0437, by =0.0001)

#Create individuals
create.inds <- function(id = NaN, length0=NaN, k1=NaN){
  inds <- data.frame(id=id, length0 = length0, k1=k1)
  inds
}

# Generate individuals
inds <- create.inds(id=1:n.initial,
        length=sample(lengths,100,replace=TRUE),    
         k1=sample(ks, 100, replace=TRUE))

# Calculate new lengths based on last and 2nd last columns and insert into next column
inds[,ncol(inds)+1] <- 326*(1-exp(-(inds[,ncol(inds)])))+
     (inds[,ncol(inds)-1]*exp(-(inds[,ncol(inds)])))

# Calculate new ks and insert into last column
inds[,ncol(inds)+1] <- sample(ks, 100, replace=TRUE)

我们将不胜感激,如果您认为有更好的书写方式,请告诉我。

1 个答案:

答案 0 :(得分:0)

我认为您要问的是一个简单的循环:

for (i in 1:100) { #replace 100 with the desired times you want this to excecute
 inds[,ncol(inds)+1] <- 326*(1-exp(-(inds[,ncol(inds)])))+
     (inds[,ncol(inds)-1]*exp(-(inds[,ncol(inds)])))

# Calculate new ks and insert into last column
inds[,ncol(inds)+1] <- sample(ks, 100, replace=TRUE) 
}
相关问题