Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将复杂for循环替换为apply in R_R_Loops_Apply_Linear Programming - Fatal编程技术网

将复杂for循环替换为apply in R

将复杂for循环替换为apply in R,r,loops,apply,linear-programming,R,Loops,Apply,Linear Programming,我试图用R中的apply函数族(如果可能的话)替换运行了一百万次的for循环。我被告知,这将大大加快这一进程,因此我认为我将接触到专家界。问题是: @汉斯沃纳指出了一个线性规划的解决方案,解决了我之前的一个问题,我试图找到合适的人来做这项工作 #导入D中的数据 str(D) #准备约束矩阵 A for循环本身不太可能是这里的瓶颈。一次呼叫lp需要多长时间。将其乘以计划运行的次数。您(使用这些工具)无法在比这更短的时间内运行它。切换到*apply可能不会节省很多时间。但是,如果你有一个多核机器,

我试图用R中的apply函数族(如果可能的话)替换运行了一百万次的for循环。我被告知,这将大大加快这一进程,因此我认为我将接触到专家界。问题是:

@汉斯沃纳指出了一个线性规划的解决方案,解决了我之前的一个问题,我试图找到合适的人来做这项工作

#导入D中的数据
str(D)
#准备约束矩阵

A for循环本身不太可能是这里的瓶颈。一次呼叫
lp
需要多长时间。将其乘以计划运行的次数。您(使用这些工具)无法在比这更短的时间内运行它。切换到
*apply
可能不会节省很多时间。但是,如果你有一个多核机器,使用<代码>并行包的代码> McApple < /C>或类似的工具肯定会加速事情的发展。C++是一个解决方案库。如果真的需要那么长的时间,那么通过Rcpp来完成可能是一种方式。
# Import data in D
    str(D)

# Prepare constraint matrix
A <- matrix(0, nrow = 5, ncol = 299)
A[1, c(1:27, 279:299)] <- 1     # Plumbers
A[2, 28:97] <- 1                # Electricians
A[3, 98:190] <- 1               # Const Workers
A[4, 191:278] <- 1              # Cleanup
A[5, ] <- D$Cost                # cost <= 100000

# Prepare input for LP solver
objective.in <- D$Value
const.mat <- A
const.dir <- c(">=", ">=", ">=", ">=", "<=")
const.rhs <- c(1, 2, 2, 2, 100000)

# Now solve the problem
require(lpSolve)
sol <- lp(direction = "max", objective.in, # maximize objective function
        const.mat, const.dir, const.rhs,   # constraints
        all.bin = TRUE)                    # use binary variables only

# View the solution
sol

## 100000
inds <- which(sol$solution == 1)
D[inds, ]

## Success: the objective function is 589
sum(D$Cost[inds])
for(i in 1:million)
{
# Change objective.in

sol <- lp(direction = "max", objective.in, # maximize objective function
            const.mat, const.dir, const.rhs,   # constraints
            all.bin = TRUE)                    # use binary variables only

# Do some comparisons and MAYBE save the solution
}