使用 r 中的链接变量创建模拟循环

问题描述 投票:0回答:1

我使用盖革包中的 sim.bd 函数根据灭绝和物种形成率来模拟物种丰富度。我需要运行模拟 1000 次。当你运行它时,一旦你得到 3 列数据:

    time   n
[1]   1    6
[2] .....

模拟运行1000次后我想要的是每次的平均值n。我知道要创建一个循环才能走到这一步:

c.sprich<-c()   
for (i in 100) 
{
pop.carn <- sim.bd(b=0.39, d=0.55, n0=4, times=66)
c.sprich[i]<- ##I don't know what command to put here to get the average n linked to each time 
}

有什么想法吗?

我尝试过像 length() 这样的函数,但这会导致所有内容的总和,而不是我想要的

r average
1个回答
0
投票

我建议这样的方法:

library(geiger)
sim <- replicate(1e4, sim.bd(b = .39, d = .55, n0 = 4L, times = 1:66L)[, "n"]) |>
  {\(x) cbind("time" = 0L:66L, "AveragePerN" = round(rowMeans(x), digits = 3L)) }()

给予

> head(sim)
     time AveragePerN
[1,]    0       4.000
[2,]    1       3.311
[3,]    2       2.808
[4,]    3       2.450
[5,]    4       2.049
[6,]    5       1.740
© www.soinside.com 2019 - 2024. All rights reserved.