【发布时间】:2021-07-21 21:03:42
【问题描述】:
谁能帮我重写代码不使用for循环?目标是找到最大化 calcProfit的支出价值。
在本例中,“calcVolume”和“calcProfit”是虚拟函数。在我的真实项目中:
- 它们很复杂很复杂
- 'calcProfit' 将是凹形的
- 运行此循环将花费超过 1 分钟(因此对用户来说是不可取的)
set.seed(123)
spend = 150000
unit.x <- spend/10 # x axis (unit)
max.x <- spend*2 # x axis (max)
calcVolume <- function(spend) {
runif(1,0,1)*spend
}
calcProfit <- function(vol) {
runif(1,0,1)*vol
}
out <- as.data.frame(matrix(data = NA, nrow = 21, ncol = 2))
cnt <- 1
for (step.x in seq(0, max.x, by = unit.x)) {
out[cnt, 1] <- step.x
out[cnt, 2] <- calcVolume(step.x)
out[cnt, 3] <- calcProfit(out[cnt, 2])
cnt <- cnt + 1
}
【问题讨论】:
-
您在寻找
help("optimize")还是help("optim")? -
不完全。我进行了编辑以澄清我的问题。是的,我正在尝试优化 calcProfit,但这取决于 calcVolume。不确定我们是否可以使用“优化”来做到这一点。
标签: r for-loop optimization