1. foreach
package
The foreach
package provides a new looping construct for executing R code repeatedly. The main reason for using the foreach
package is that it supports parallel execution
parameters to be introduced:
foreach
: specify the variables to iterate over%do%
: binary operators, execute the R expression sequentially%dopar%
: binary operators, execute the R expression using the currently registered backend%:%
: nesting operators, create nested foreach loops
Usage:
foreach(..., .combine, .init, .final=NULL, .inorder=TRUE, .multicombine=FALSE, .maxcombine=if (.multicombine) 100 else 2, .errorhandling=c('stop', 'remove', 'pass'), .packages=NULL, .export=NULL, .noexport=NULL, .verbose=FALSE)
.combine
:c
is useful for concatenating the results into a vector;cbind
andrbind
can combine vectors into a matrix;+
and*
can be used to process numeric data. By default, the results are returned in a list.
2. Examples
> # foreach package
>
> library(foreach)
>
> foreach(i=1:3)%do% sqrt(i)
[[1]]
[1] 1
[[2]]
[1] 1.414214
[[3]]
[1] 1.732051
> foreach(i=1:3, .combine = "c")%do% sqrt(i)
[1] 1.000000 1.414214 1.732051
> foreach(i=1:3, .combine = "+")%do% sqrt(i)
[1] 4.146264
> foreach(i=1:3, .combine = "*")%do% sqrt(i)
[1] 2.44949
>
> library(MASS)
> foreach(1:10, .combine = "rbind")%do% mvrnorm(1,rep(0,3), diag(3))
[,1] [,2] [,3]
result.1 1.5630549 1.02659189 1.2804769
result.2 -1.6957373 0.67580662 -0.9537855
result.3 -2.0787570 0.51637372 0.7091263
result.4 -0.1867845 -0.06440223 -1.1717261
result.5 0.3833949 -0.59977010 0.3472026
result.6 -1.8356754 1.77720778 0.1851016
result.7 0.6922240 -0.90876651 0.3539157
result.8 1.1140055 -0.44083003 -1.3054194
result.9 0.5193093 0.34136464 1.7463392
result.10 0.9659776 -1.01835620 0.4123284
> foreach(i=1:3, .combine = "c")%:%
+ foreach(j=1:5, .combine="+")%do%{
+ rnorm(1)
+ }
[1] 0.8171045 5.3792075 1.3293824
reference:
https://cran.r-project.org/web/packages/foreach/vignettes/nested.pdf