【发布时间】:2021-05-07 08:06:27
【问题描述】:
我知道不创建可重现的示例是 StackOverflow 的罪过,但我不确定这是否有必要。以下嵌套循环需要 40 分钟才能运行。 ptptdata 中有大约 6,300 行,代表一个人。该循环只是将某人的年龄和持续时间拉到退休。它运行一个循环,增加通货膨胀(取自 infdata)和价值增长(静态 2.5%)直到持续时间。一旦循环结束,它会将最终工资和年龄保存回 ptptdata。然后它向下移动到下一个个体并再次执行此操作。我读过使用向量而不是添加回 ptptdata 会更快,但我不确定我是否遵循如何做到这一点。我原以为代码会很慢,但我还有很多东西要添加,如果这个简单的过程需要这么长时间,这将是不可行的。
ptptdata$FinalSalary <- 0
ptptdata$FinalAge <- 0
trial <- 1
for(row in 1:nrow(ptptdata)){ ### Tells model to complete loop for each individual
i <- 1 ## Starting point for each individual
dur <- as.numeric(ptptdata[row,"DurationRet"])
age <- as.numeric(ptptdata[row, "Age"])
salary <- as.numeric(ptptdata[row,"Current Salary"])
while (i<=dur){
inflation <- as.numeric(infdata[infdata$Item == 'Inflation' & infdata$Scenario == as.factor(trial),i+2])
salboy <- salary
ageboy <- age
salary <- salboy * (1+meritgrowth)* (1+inflation)
age <- age + 1
i <- i + 1
}
ptptdata[row,"FinalSalary"]<-salary
ptptdata[row,"FinalAge"]<-age
}
【问题讨论】:
-
我从未使用过 R,但在我看来,您正在对字符串数据进行所有数学运算,并且还在最内层循环中进行字符串比较。将相关数据提取为数字向量/矩阵并对其进行操作不是更好吗?
标签: r performance loops