首页 > 解决方案 > 我怎样才能将这两行代码重复 100 多次?

问题描述

我还是编程世界的新手,正在寻找一些关于我正在为随着时间的推移为个体动物生长而构建的模型的指导。我正在使用的代码的目标是 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)

任何和所有的帮助将不胜感激,如果您认为有更好的方法来写这个,请告诉我。

标签: rfunctionmodel

解决方案


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

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) 
}

推荐阅读