The “clusterApply” Function in R

  • Package: parallel

  • Purpose: Apply a function to each node in a cluster in parallel.

  • General class: Parallel computing

  • Required argument(s):

    • cl: The cluster object created with makeCluster.

    • x: A list or vector to be divided among the nodes for processing.

    • fun: The function to be applied to each node.

  • Notable optional arguments:

    • ...: Additional arguments to be passed to the function.

  • Example:

  • # Load the parallel package
    library(parallel)

    # Create a cluster with 4 nodes
    cl <- makeCluster(4)

    # Define a function to square a number
    square <- function(x) { return(x^2) }

    # Apply the function to each node in the cluster
    result <- clusterApply(cl, 1:10, square)

    # Stop the cluster
    stopCluster(cl)

    # View the result
    print(result)

  • In this example, we create a cluster cl with 4 nodes using the makeCluster function. We define a function square to square a number. Then, we use clusterApply to apply the square function to the numbers 1 to 10 in parallel across the nodes in the cluster. The result is printed to the console.

Previous
Previous

The “clusterSplit” Function in R

Next
Next

The “parCapply” Function in R