R中的循环问题

Trouble with loop in R

我对 R 编程还是很陌生,循环似乎总是让我感到困惑。我想做的是将我的产能与需求进行比较,并取两个值中较小的一个来计算利润。在下面的例子中,第 6 个位置的产能是 55,000,但需求是 56,074.44,所以我只能生产我的产能。

当前代码:

UnitCost <- 3.70
Capacity <- c(30000, 35000, 40000, 45000, 50000, 55000, 60000)

Profit <- c()
for (i in 1:length(Capacity)) {
  Demand <- rnorm(n = 1, mean = 50000, sd = 12000)
  Revenue[i] <- min(Demand, Capacity[i]) * UnitCost
  Profit[i] <- sum(Revenue[i])
}
demand
Profit

输出:

> Demand
[1] 56074.44
> Profit
[1] 111000.0 129500.0 148000.0 166500.0 185000.0 118181.7 207475.4

需要输出:

> Demand
[1] 56074.44
> Profit
[1] 111000.0 129500.0 148000.0 166500.0 185000.0 203500.0 207475.4

您提供的代码不完整。我有几个问题 -

  • 你的需求是一个常数吗?为什么要在循环中为其分配一个值?
  • 在您分配 Revenue 值的行中 'd' 是什么?

我假设 'd' 是需求,我重新编写了您的代码,它似乎提供了所需的输出。

UnitCost <- 3.70
Capacity <- c(30000, 35000, 40000, 45000, 50000, 55000, 60000)
demand <- 56074.44

Profit <- c()
Revenue <- c()

for (i in 1:length(Capacity)) {
    Revenue[i] <- min(demand, Capacity[i]) * UnitCost
    Profit[i] <- sum(Revenue[i])
}

demand
Profit

输出-

demand
[1] 56074.44
Profit
[1] 111000.0 129500.0 148000.0 166500.0 185000.0 203500.0 207475.4

首先我会使用sapply代替for循环,如下:

sapply(Capacity, function(cap){
  sum(min(demand, cap) * UnitCost)
})

这将为您的问题中指示的 demand 提供以下输出:

# 111000.0 129500.0 148000.0 166500.0 185000.0 203500.0 207475.4

编辑:要将此应用于多年需求,您可以执行以下操作:

num.years <- 1:5
sums <- data.frame(t(sapply(num.years, function(i){
  set.seed(i-1)
  demand <- rnorm(n = 1, mean = 50000, sd = 12000)
  sapply(Capacity, function(cap){
    sum(min(demand, cap) * UnitCost)
  })
})))
row.names(sums) <-  paste0("Year_", num.years)
colnames(sums) <-  Capacity
sums

这将为您提供以下输出:

#          30000   35000     40000     45000     50000     55000     60000
# Year_1  111000  129500  148000.0  166500.0  185000.0  203500.0  222000.0
# Year_2  111000  129500  148000.0  166500.0  180392.6  180392.6  180392.6
# Year_3  111000  129500  148000.0  160263.8  160263.8  160263.8  160263.8
# Year_4  111000  129500  148000.0  166500.0  185000.0  203500.0  222000.0
# Year_5  111000  129500  145352.7  145352.7  145352.7  145352.7  145352.7

希望对您有所帮助。

实际上 *apply 函数不需要 for 循环,pmin 可以帮助您获得所需的输出

Demand <- rnorm(length(Capacity),mean = 50000, sd = 12000)
Profit <- pmin(Capacity,demand) * UnitCost

这样

> Profit
[1] 111000.0 129500.0 148000.0 166500.0 185000.0 203500.0 207475.4