假设我有一个100棵树的年龄向量.然后,我将这些树木老化5年、10年、15年和20年,以创建今年和future 四个5年规划期的树龄矩阵.
但随后,我决定砍伐其中一些树木(每个规划期仅10棵),记录在T/F值矩阵中,其中T是收获的,F不是(树木不能收获两次).
age.vec <- sample(x = 1:150, size = 100, replace = T) # create our trees
age.mat <- cbind(age.vec, age.vec+5, age.vec + 10, age.vec + 15, age.vec + 20) # grow them up
x.mat <- matrix(data = F, nrow = 100, ncol = 5) # create the empty harvest matrix
x.mat[cbind(sample(1:100, size = 50), rep(1:5, each = 10))] <- T # 10 trees/year harvested
因此,当年收获的树木年龄变为零:
然后,我想在接下来的时间里再次对收获的树木进行老化.E、 g.如果一棵树在第一个计划期收获,在第二个计划期(5年后),我希望树的年龄为5岁,然后在第三个计划期(10年后),我希望树的年龄为10岁.我已在以下for循环中成功实现了这一点:
for (i in 2:5){ # we don't need to calculate over the first year
age.mat[,i]<-age.mat[,i-1]+5L # add 5 to previous year
age.mat[x.mat[,i],i] <- 0L # reset age of harvested trees to zero
}
然而,这是一种笨重而缓慢的工作方式.有没有办法更快地实现这一点(即没有for循环)?它也在函数中实现,这意味着使用"apply"实际上会减慢速度,因此需要直接对其进行矢量化.这是我迭代了数千次的东西,所以速度至关重要!
非常感谢.