我正在模拟人工林的生长。
我必须每年(从0年到6年的列)填充10棵树(每行一棵)的df。我有一个来自“ growthmodels”包的函数,该函数可计算每年的树的体积或创建一个向量,并包含年份范围内的所有值。我有每年每棵树的年龄的df(有些树死了,必须重新种植,所以它们的年龄从零开始)。
这里是问题的简化版本:
volume <- data.frame(matrix(ncol = 6, nrow = 10))
age <- data.frame("y0" = rep(0, 10))
for (y in 2:6){
d <- sample(1:10, 1)
d0 <- 10-d
age <- cbind(age, c(age[1:d, y-1] + rep(1, d), rep(0, d0)))
names(age)[y] <- paste0("y", y-1)
}
library(growthmodels)
growth <- chapmanRichards(t=1:5, alpha=3, m=.4, k=.4, beta=1)
我发现了以下方法,但是执行起来超级慢。想象一下,我必须针对更多物种和100种具有多种生长速度的随机病例运行它。你有建议吗?
#inputing normal growth
for (y in 2:6){
for (t in 1:nrow(volume)) {
volume[t,y] <- chapmanRichards(t=age[t,y], alpha=3, m=.4, k=.4, beta=1)
}
}
Base-R中的类似结果与循环相同。
apply(age,2, function(y) sapply(y,function(x) chapmanRichards(t=x, alpha=3, m=.4, k=.4, beta=1) ))
y0 y1 y2 y3 y4 y5
[1,] 0 0.4720002 1.1098773 1.650880 2.0600919 2.354331
[2,] 0 0.4720002 1.1098773 1.650880 2.0600919 2.354331
[3,] 0 0.4720002 1.1098773 1.650880 2.0600919 2.354331
[4,] 0 0.0000000 0.4720002 1.109877 1.6508796 2.060092
[5,] 0 0.0000000 0.4720002 0.000000 0.4720002 1.109877
[6,] 0 0.0000000 0.4720002 0.000000 0.4720002 1.109877
[7,] 0 0.0000000 0.4720002 0.000000 0.4720002 0.000000
[8,] 0 0.0000000 0.0000000 0.000000 0.4720002 0.000000
[9,] 0 0.0000000 0.0000000 0.000000 0.0000000 0.000000
[10,] 0 0.0000000 0.0000000 0.000000 0.0000000 0.000000
编辑:以发表您的评论:
您可以通过以下方式实现
rbind(
apply(age[1:3,],2, function(y) sapply(y,function(x) chapmanRichards(t=x, alpha=3, m=.4, k=.4, beta=1))),
apply(age[4:6,],2, function(y) sapply(y,function(x) chapmanRichards(t=x, alpha=3, m=.4, k=.4*7, beta=1))),
apply(age[7:10,],2, function(y) sapply(y,function(x) chapmanRichards(t=x, alpha=3, m=.4, k=0, beta=1)))
)