How to use multicore with loops in R

前端 未结 1 1456
栀梦
栀梦 2020-12-22 13:35

I need to speed up this built in loops how can I do please ?

for(M_P in 0:9)
{
for(M_D in 0:(9-M_P))
{
for(M_A in 0:(9-M_P-M_D))
{
  for(M_CC in 0:(9-M_P-M_         


        
相关标签:
1条回答
  • 2020-12-22 14:31

    The variables M_xx, G_xx, S_xx and Q_xx are independent. Also, there is a lot of coincident values generated. I've split these 4 variables in separate loops, then I've generated all combinations considering only unique values. See the code:

    M <- NULL
    
    for(M_P in 0:9) for(M_D in 0:(9-M_P)) for(M_A in 0:(9-M_P-M_D)) for(M_CC in 0:(9-M_P-M_D-M_A)) for(M_CD in (9-M_P-M_D-M_A-M_CC))
    {
        M[length(M)+1] <- 1.1*M_P+2.1*M_D+3.1*M_A+4.1*M_CC+4*M_CD
    }
    
    G <- NULL
    
    for(G_D in 0:9) for(G_A in 0:(9-G_D)) for(G_CC in 0:(9-G_D-G_A)) for(G_CD in (9-G_D-G_A-G_CC))
    {
        G[length(G)+1] <- 2*G_D+5*G_A+1.5*G_CC+3*G_CD
    }
    
    S <- NULL
    
    for(S_D in 0:9) for(S_A in 0:(9-S_D)) for(S_CC in 0:(9-S_D-S_A)) for(S_CD in (9-S_D-S_A-S_CC))
    {
        S[length(S)+1] <- 5*S_D+4*S_A+3*S_CC+6*S_CD
    }
    
    Q <- NULL
    
    for(Q_P in 0:3) for(Q_D in 0:(3-Q_P)) for(Q_A in 0:(3-Q_P-Q_D)) for(Q_CC in 0:(3-Q_P-Q_D-Q_A)) for(Q_CD in (3-Q_P-Q_D-Q_A-Q_CC))
    {
        Q[length(Q)+1] <- 2*Q_P+3*Q_D+2.2*Q_A+3*Q_CC+4*Q_CD
    }
    
    max(apply(expand.grid(unique(M), unique(G), unique(S), unique(Q)), 1, sum))
    
    0 讨论(0)
提交回复
热议问题