首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将嵌套的for循环替换为mapply

将嵌套的for循环替换为mapply
EN

Stack Overflow用户
提问于 2017-12-07 22:28:45
回答 2查看 384关注 0票数 1

我是R的初学者,我正在使用R studio的Cplex解决线性规划问题。我的模型中的一个约束是Xl(i,j,t) <= D(i,j,t)。我可以使用嵌套的for循环来实现这一点,该循环的维度很小(16X16X6)。但我想运行我的模型更大的模型,更像2500X2500X60。我需要节省内存,并且比嵌套的for循环运行得更快。我想过使用apply,但我不知道如何让它工作。任何帮助都将不胜感激!

代码语言:javascript
复制
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

这是另一个限制。

代码语言:javascript
复制
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)))
      }
  }
}

我试着这样做:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2017-12-08 01:37:18

您可以使用以下命令获得相同的输出

代码语言:javascript
复制
T <- horizon*locations*locations
Bmat <- cbind(matrix(0, nrow=T, ncol=T), diag(1, nrow=T, ncol=T))
identical(Amat, Bmat)
# TRUE
票数 2
EN

Stack Overflow用户

发布于 2017-12-08 12:03:14

我认为你需要做的是制作一个矢量化的函数,给出相同的输出(参见?Vectorize)。下面的代码比你的快五百倍。

在您的实际问题中,可能需要使用<<-而不是<- (请参阅?"<<-")

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47697281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档