Marius Hofert
2011-May-11 21:44 UTC
[R] foreach(): how to do calculations "between" two foreach loops?
Dear expeRts, is it possible to carry out calculations between different foreach() calls? As for nested loops, you want to carry out calcuations not depending on the inner loop only once and not for each iteration of the innermost loop. Cheers, Marius library(foreach) foreach(i=1:3) %:% foreach(j=1:2) %do% { i <- i+1 print(paste(i,j)) } foreach(i=1:3) %:% i <- i+1 # lengthy calculation which has to be done only once, not for each j foreach(j=1:2) %do% { print(paste(i,j)) }
Steve Lianoglou
2011-May-12 19:55 UTC
[R] foreach(): how to do calculations "between" two foreach loops?
Hi, On Wed, May 11, 2011 at 5:44 PM, Marius Hofert <m_hofert at web.de> wrote:> Dear expeRts, > > is it possible to carry out calculations between different foreach() calls? > As for nested loops, you want to carry out calcuations not depending on the inner > loop only once and not for each iteration of the innermost loop. > > Cheers, > > Marius > > > library(foreach) > > foreach(i=1:3) %:% > ? ?foreach(j=1:2) %do% { > ? ? ? ? ? ?i <- i+1 > ? ? ? ?print(paste(i,j)) > ? ?} > > foreach(i=1:3) %:% > ? ?i <- i+1 # lengthy calculation which has to be done only once, not for each j > ? ?foreach(j=1:2) %do% { > ? ? ? ?print(paste(i,j)) > ? ?}If I understand your question well, one solution might be to break it into two parallized parts, eg: R> lengthy.calculation.i <- foreach(i=1:3) %dopar% someIntenseFunction(i) R> foreach(i=1:3) %:% foreach(j=1:3) %dopar% { anotherIntenseFunction(length.calculation.i[i], j) } I believe the left and right hand side of the %:% "operator" need a "foreach" object, so your original incantation wouldn't work. -steve -- Steve Lianoglou Graduate Student: Computational Systems Biology ?| Memorial Sloan-Kettering Cancer Center ?| Weill Medical College of Cornell University Contact Info: http://cbio.mskcc.org/~lianos/contact