The “foreach” Function in R

  • Package: foreach

  • Purpose: Iterate over elements in a collection in parallel or sequentially.

  • General class: Iteration

  • Required argument(s):

    • ...: The collection of elements to iterate over.

  • Notable optional arguments:

    • .combine: A function to combine the results of each iteration.

    • .packages: A character vector of packages to load in each iteration.

  • Example:

  • # Load the foreach package
    library(foreach)
    library(doParallel)

    # Register a parallel backend with 4 cores
    registerDoParallel(cores = 4)

    # Create a foreach loop for parallel processing
    result <- foreach(i = 1:10, .combine = "c") %dopar% sqrt(i)

    # View the result
    print(result)

  • In this example, we use the foreach function to iterate over the elements 1 to 10 in parallel (%dopar%), computing the square root of each element. The .combine argument specifies the function (c for concatenation) to combine the results of each iteration into a single result. The final result is then printed to the console.

Previous
Previous

The “future_map” Function in R

Next
Next

The “registerDoParallel” Function in R