Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205491

R: how to incorporate write.csv in nested foreach loop

$
0
0

I simplified the problem to below and I know in normal circumstances, I would not use nested foreach loop and I should really use nested for loop. However, I would like to know how this could be done using foreach loop or is it just impossible ?

processedAndTransformed <- function(j){
  df                    <- rnorm(25)
  return(matrix(df * j,ncol=1) )
}

# in normal circumstances, use for loop
for(j in c(2,4,7,9)){
    res <- foreach(i = 1:4,.combine = "cbind")%dopar%{
  processedAndTransformed(j)
}
    write.csv(res,file=paste("testing",j,".csv",sep=""))
} 

Now, my attempt to convert the outer for loop to foreach loop is below. Please note that the ** write.csv **function is inside the outer foreach loop but outside of the inner loop.

# below code fails
foreach(j = c(2,4,7,9))%:%
res <- foreach(i = 1:4,.combine = "cbind")%dopar%{
  processedAndTransformed(j)
}
write.csv(res,file=paste("testing",j,".csv",sep=""))

The whole thing just fails. I do not understand why and how to correct it.

Update: Should be writing to a different file.


Viewing all articles
Browse latest Browse all 205491

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>