无循环优化R代码

时间:2018-07-05 08:22:33

标签: r loops optimization parallel.foreach

我有一个脚本R,该脚本R必须处理大数据集(j大)。我已经删除了一些循环,但是我相信可以再次对其进行优化。我尝试了foreach()函数,但它给了我一些错误。我不知道如何并行化以及是否有必要。有人有主意吗?我的代码类型为:

par <- data.frame(CA=runif(n = 50, min = 70000, max = 100000),
          D=round(runif(n = 50, min = 70, max = 90),0),
          P=runif(n = 50, min = 900, max = 20000),
          A=round(runif(n = 50, min = 50, max = 70),0))

parpa <- data.frame(matrix(nrow = nrow(par), ncol = 3*V))

comp <- function(CA, D, P, A){
vect <- rep('numeric', 3*V)

b <- 1
k <- 1 
while (((b+1) <= (D+1))&(k < V)) { 
a <- b+1
b <- min((a+8-1), (D+1))
vect[c(1+4*k, 2+4*k, 3+4*k, 4+4*k)] <- c(mean(DF2$Z[a:b]), sum(DF2$X[a:b]),
                                    mean(DF2$Q[a:b]), sum(DF2$AE[a:b]))
k <- k+1
}
return(vect)                       
}

#loop
for (j in 1:nrow(par)) {

CA <- par$CA[j] 
D <- par$D[j] 
R <- 0.01*D 
P <- par$P[j] 
A <- par$A[j]
COST <- 500    
V <- 5
#DF2
DF2 <- data.frame(M=0:D)
O <- function(x) {
c <- COST*D*DF2$M/R
return(c)
}
DF2$O <- O(D)
DF2$E <- (D*DF2$M+2)/D*(D+4)
DF2$Q <- (CA-DF2$M)*D
DF2$X <- (CA-DF2$O)*(DF2$E+P)
Func <- function(x) {return(round(x/30, 2))}
DF2$Z[(A+2):(D+1)] <- unlist(sapply(DF2$E[(A+2):(D+1)], Func))

parpa[j,] <- comp(CA, D, P, A)
}

0 个答案:

没有答案