• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

R/H19-Feb-2020-1,616751

build/H03-May-2022-

demo/H19-Feb-2020-3927

inst/H12-Oct-2020-1,9991,469

man/H19-Feb-2020-541446

tests/H19-Feb-2020-440346

vignettes/H12-Oct-2020-801666

DESCRIPTIONH A D15-Oct-20201.6 KiB3635

MD5H A D15-Oct-20204 KiB7776

NAMESPACEH A D28-Mar-20201.2 KiB4745

NEWS.mdH A D11-Oct-20203.2 KiB7350

README.mdH A D29-Mar-20201.9 KiB4835

README.md

1# foreach
2
3[![CRAN](https://www.r-pkg.org/badges/version/foreach)](https://cran.r-project.org/package=foreach)
4![Downloads](https://cranlogs.r-pkg.org/badges/foreach)
5![R-CMD-check](https://github.com/RevolutionAnalytics/foreach/workflows/R-CMD-check/badge.svg)
6
7This package provides support for the foreach looping construct. Foreach is an idiom that allows for iterating over elements in a collection, without the use of an explicit loop counter. The main reason for using this package is that it supports parallel execution, that is, it can execute repeated operations on multiple processors/cores on your computer, or on multiple nodes of a cluster. Many different _adapters_ exist to use foreach with a variety of computational backends, including:
8
9- [doParallel](https://cran.r-project.org/package=doParallel): execute foreach loops on clusters created with base R's parallel package
10- [doFuture](https://github.com/HenrikBengtsson/doFuture): using the future framework
11- [doRedis](https://github.com/bwlewis/doRedis): on a Redis database
12- [doAzureParallel](https://github.com/Azure/doAzureParallel): on a compute cluster in Azure
13- and more.
14
15## Example
16
17A basic `for` loop in R that fits a set of models:
18
19```r
20dat_list <- split(iris, iris$Species)
21mod_list <- vector("list", length(dat_list))
22for(i in seq_along(dat_list)) {
23    mod_list[[i]] <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data=dat_list[[i]])
24}
25```
26
27The same using foreach:
28
29```r
30library(foreach)
31mod_list2 <- foreach(dat=dat_list) %do% {
32    lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data=dat)
33}
34```
35
36The same, but fit _in parallel_ on a background cluster. We change the `%do%` operator to `%dopar%` to indicate parallel processing.
37
38```r
39library(doParallel)
40registerDoParallel(3)
41mod_list2 <- foreach(dat=dat_list) %dopar% {
42    lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data=dat)
43}
44
45stopImplicitCluster()
46```
47
48