【发布时间】:2019-08-01 15:27:35
【问题描述】:
我正在做一个项目,为此我编写了一些 R 代码。但是,我在尝试改进运行时遇到了一些麻烦。
我使用了两个数据框。必须注意的是,可以在随机行上找到匹配的观测值。
- df1(称为“ac”)包含历史需求实际值,其中包含“Region”、“Product”、“time”和“ac_qty”列。
- df2(称为“fc”)包含带有“Region”、“Product”、“time”和“fc_qty”列的预测。
我想创建第三个数据框(称为“er”),其中包含每个特定区域/产品/时间组合的所有错误 (er_qty)。我已经成功了,使用以下代码:
# Examples of data frames 'ac' and 'fc':
ac <- data.frame("Region" = c("R1", "R2", "R3"),
"Product" = c("P1", "P2", "P3"),
"time" = c(1, 2, 2),
"ac_qty" = c(4, 2, 3) )
fc <- data.frame("Region" = c("R2", "R1", "R3"),
"Product" = c("P2", "P1", "P3"),
"time" = c(2, 1, 2),
"fc_qty" = c(2, 1, 3) )
# Copy data frame with forecasts, and expand (separated data frames for later processing)
er <- fc
# Finding corresponding ac_qty for fc_qty with given Region/Product/time:
for (i in 1:length(er$fc_qty)) {
er$ac_qty[i] <- ac$ac_qty[ac$Region == er$Region[i] & ac$Product== er$Product[i] & ac$time == er$time[i] ]
}
er$er_qty <- er$fc_qty- er$ac_qty
因为 for 循环需要在数据框中迭代超过 200,000 行,所以计算所有值需要很长时间。我需要大幅减少脚本的运行时间。我尝试使用 with() 函数,但验证后导致错误值。
er$ac_qty<- with(ac, ac_qty[which(Region == er$Region & Product == er$Product & time == er$time)])
此外,上面的代码给了我这个警告:“更长的对象长度不是更短的对象长度的倍数”
找到与预测 (fc_qty) 相匹配的需求量 (ac_qty) 值的最佳方法是什么,该预测 (fc_qty) 的区域、产品和时间列具有相同的变量?
谢谢。
【问题讨论】:
-
请制作一个可重现的小例子,以及输出应该是什么样子。
-
我已经在描述中提供了