【问题标题】:replace a nested for loop with mapply用 mapply 替换嵌套的 for 循环
【发布时间】:2018-05-21 16:35:41
【问题描述】:

我是 R 的初学者。我正在使用 R Studio 的 Cplex 进行线性编程来求解模型。我的模型中的一个约束是 Xl(i,j,t)

location <-16
horizon <-6
Amat <- NULL
Xe_null <- array(0, dim = c(locations, locations, horizon))
Xl_null <- array(0, dim = c(locations, locations, horizon))
Xl      <- array(0, dim = c(locations, locations, horizon))
Xl <- Xl_null
for (t in 1:horizon) {
  for (j in 1:locations) {
    for (i in 1:locations) {
      Xl[i,j,t] <- 1
      Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl)))
      Xl <- Xl_null 
 } } }
dim(Amat) # 1536 3072

这是另一个约束。

R       <- array(, dim=c(locations, horizon, horizon))
R_null  <- array(, dim=c(locations, horizon, horizon))
R <- R_null
Xe <- Xe_null
Xl <- Xl_null
#
for (t in 1:(horizon-1)) {
  for (tp in (t+1):horizon) {
    for (j in 1:locations)     {
      for (i in 1:locations)      {
        if ((tp-t) ==Travel_time[i,j]) 
        {
          Xe[i,j,t]=1
          Xl[i,j,t]=1
        } 
      }
      R[j,tp,t] = 1
      R[j,tp,t+1] = -1
      Amat <- rbind(Amat, c(as.vector(Xe), as.vector(Xl),as.vector(R)))
      }
  }
}

我尝试这样做:

Xl = function(ii,jj,tt){1}
t =c(1:horizon)
i =c(1:locations)
j =c(1:locations)
output_Xl = apply(expand.grid(i,j,t),1,function(x,y,h) Xl(x[1],x[2],x[3]))
Xl_new <- array(output_Xl, dim = c(locations, locations, horizon))
Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl_new)))
dim(Amat) # 1 3072

【问题讨论】:

  • Xl_nullXe_null是同一个对象还是Xe_null是原始数据?
  • 是的,Xl_null 和 Xe_null 都是空的零。

标签: r for-loop apply sparse-matrix nested-loops


【解决方案1】:

我认为您需要的是创建一个矢量化函数以提供相同的输出(请参阅?Vectorize)。下面的代码比你的快五百倍。
在你真正的问题上,也许你需要使用&lt;&lt;-而不是&lt;-(见?"&lt;&lt;-"

my_func <- function(a, b, c){
  Xl[a, b, c] <- 1
  c(as.vector(Xe_null), as.vector(Xl))
}

vectorized_my_func <- Vectorize(my_func, c("a", "b", "c"))

arg_df <- expand.grid(1:locations, 1:locations, 1:horizon)
res <- vectorized_my_func(arg_df[,1], arg_df[,2], arg_df[,3])

identical(Amat, t(res))    # TRUE

# your code
##   user  system elapsed 
## 77.538  18.293  97.056 

# my code
##   user  system elapsed 
###  0.137   0.051   0.189 

【讨论】:

  • 感谢您的帮助和编辑我的帖子的建议。非常有帮助!谢谢:)
  • 嗨,我有一个后续问题。当我切换位置
【解决方案2】:

你可以得到相同的输出

T <- horizon*locations*locations
Bmat <- cbind(matrix(0, nrow=T, ncol=T), diag(1, nrow=T, ncol=T))
identical(Amat, Bmat)
# TRUE

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 2019-06-06
    • 2016-07-14
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多