r - 我怎样才能将这两行代码重复 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)
任何和所有的帮助将不胜感激,如果您认为有更好的方法来写这个,请告诉我。
解决方案
我认为您要问的是一个简单的循环:
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)
}
推荐阅读
- eclipse - 什么是 Eclipse IDE 中的“已删除”文件夹?
- sails.js - 将 Sails 应用程序捆绑到单个可执行文件中
- excel - vba 函数的结果未刷新
- apache-spark - 如何将 UDAF 与 groupby-aggregate 表达式中的函数结合起来?
- javascript - 简单的用户脚本很慢,有时无法正常工作
- google-apps-script - 尝试在 Postman 中连接 Google Oath2
- sql - oracle sql中的to_timestamp未处理空值
- c - 在中序树遍历中将节点推送到堆栈而不是它们的值
- selenium - Kotlin、Cucumber 和 Selenium - Kotlin 无法与元素交互
- laravel - Laravel 批量邮件队列(按数量和时间划分)