2017-06-13 57 views
0

我有一个foreach循环在我的代码中以减少运行时间。我面临的问题是,我没有得到输出中的所有输入记录。以下是代码片段。并行化(foreach)在R不工作

# my_df has 100 records 
    library(doMC) 
    library(foreach) 
    no_cores <- detectCores() 
    registerDoMC(no_cores) 
    # nrow(my_df)=100 
    output <- foreach(combo = 1:nrow(my_df),.combine=rbind) %dopar% 
    { 
    df <- my_df[combo,] #taking 1 row at a time 

      ### do some operations #### 
     score <- sum(another_df$score1+another_df$score2) 

    if(score>score_cutoff){ 
    df$score <- score   
    }else{ 
    df$score <- 0} 

    df; #rbinding *df* to *output* 
    } 

输出数据帧应该包含100条记录,但是我得到的记录(小于100每次)的随机数。我多次使用foreach,但这是第一次发生这种情况。

有人可以帮我解决这个问题吗? 在此先感谢。

+0

我假设你在'my_df'进行计算?你能否详细说明你的业务是什么? – Val

+0

@Val,我编辑了问题中的代码。我正在做的是计算_SCORE_并将该值添加到_df_ – santhoshverma

+0

@santhoshverma:你在哪里声明'another_df'?在“foreach”声明之前? 'another_df'的一般格式是什么? 2列data.frame? – CPak

回答

0

因此对于foreach您可以在索引i上同步。在你的情况下,这将是你的数据的行数my_df

你做的每一个计算都将是列表output的一个元素,你使用rbind将它们绑定在一起。到现在为止还挺好。

我无法真正说出你是如何得到你的结果的,但通常我不认为在foreach循环中分配如此多的变量是一个好主意。

这是我会怎么解决呢,结果看起来不错(有100行):

library(doParallel) 
no_cores <- detectCores() 

cl <- makeCluster(no_cores) 
registerDoParallel(cl) 

# simulate your data  
set.seed(42) 
my_df <- data.frame(A=sample(1:1000,100),B=sample(1:1000,100)) 

cutoff <- 500 

output <- foreach(i = 1:nrow(my_df),.combine=rbind) %dopar% 
{ 

    data.frame(A=my_df$A[i],B=my_df$B[i],Score=ifelse(my_df$A[i]+my_df$B[i] > cutoff,my_df$A[i]+my_df$B[i],0)) 

} 

stopCluster(cl)