ZetCode

R parallel computing

last modified November 20, 2026

A single R process uses one core, even when the machine has many. The parallel package, which ships with every R installation, lets a script spread independent work over several cores and join the results afterwards. It offers two mechanisms: forked child processes through mclapply, available on Unix-like systems, and socket clusters built with makeCluster, available everywhere. This article covers both, along with the number of workers, reproducible random numbers, and a complete example that fits a model per group. The examples use R 4.5.2 and parallel 4.5.2.

Forking with mclapply

mclapply is the parallel version of lapply. It takes a vector or a list and a function, starts the requested number of child processes, and gives each child a share of the elements. The results come back as a list in the same order as the input, so the call can replace lapply without changing the code that consumes the result.

forking.R
library(parallel)
values <- 1:4
serial <- lapply(values, function(v) v ^ 2)
parallel <- mclapply(values, function(v) v ^ 2, mc.cores = 2)
cat("serial:", unlist(serial), "\n")
cat("parallel:", unlist(parallel), "\n")
cat("identical:", identical(serial, parallel), "\n")

Both calls compute the same four squares. mc.cores = 2 asks for two workers, and identical confirms that the serial and parallel results have the same values and the same shape. A fork copies the parent process, so the child already has every object in memory. The copy is lazy: pages are shared until one side writes to them, which keeps the cost of starting a worker low.

$ Rscript forking.R
serial: 1 4 9 16 
parallel: 1 4 9 16 
identical: TRUE 

Choosing the number of workers

detectCores reports how many cores the operating system makes available, and getOption("mc.cores", 2L) reports the default that mclapply uses when mc.cores is not given. The script below prints the logical and physical counts and the option. Forking is not available on Windows, where mclapply falls back to a single process.

cores.R
library(parallel)
cat("logical cores:", detectCores(), "\n")
cat("physical cores:", detectCores(logical = FALSE), "\n")
cat("mc.cores option:", getOption("mc.cores", 2L), "\n")

The numbers depend on the machine, so this section has no output block; run the script to see your own counts. A logical count includes hyperthreads, and a physical count does not. Using every reported core is rarely the best choice, because the parent process, the operating system, and other programs need time too. A common rule is to leave one core free, and to set options(mc.cores = 2) once when a script should use a fixed number regardless of the hardware.

Socket clusters

A socket cluster starts fresh R processes and talks to them over connections, so it works on every platform. makeCluster(2) creates two workers. A new worker does not know the objects in the parent, so clusterExport copies the named values to every worker. parLapply then runs a function on each element, and stopCluster shuts the workers down.

sock-cluster.R
library(parallel)
cl <- makeCluster(2)
values <- c(4, 9, 16, 25)
clusterExport(cl, "values")
roots <- parLapply(cl, values, function(v) sqrt(v))
stopCluster(cl)
cat("roots:", unlist(roots), "\n")
cat("cluster class:", class(cl), "\n")

The workers receive a copy of values, compute the square roots, and return them in the original order. The class of the cluster object is SOCKcluster, which records the connection type; the second class, cluster, is the general marker used by the package. Changes made to an exported object inside a worker stay in that worker. Only the values returned by the function travel back to the parent.

$ Rscript sock-cluster.R
roots: 2 3 4 5 
cluster class: SOCKcluster cluster 

Applying over several arguments

clusterApply is the cluster version of lapply: each element of the vector is passed to one call of the function, and the results come back as a list. parSapply is the simplifying version: it calls simplify2array on the list of results and returns a vector or a matrix instead of a list. The next script uses both functions on the same cluster.

cluster-apply.R
library(parallel)
cl <- makeCluster(2)
labels <- clusterApply(cl, 1:3, function(i) paste("task", i))
sums <- parSapply(cl, 1:4, function(i) sum(1:i))
stopCluster(cl)
cat("labels:", unlist(labels), "\n")
cat("sums:", sums, "\n")

The three labels are built by three calls and collected into a list. parSapply returns the four sums as a numeric vector, because every result has the same length. If the results had different lengths, the simplifying step would return a list, which is the same rule that sapply follows. clusterMap and parRapply cover the remaining combinations of several arguments and matrix rows.

$ Rscript cluster-apply.R
labels: task 1 task 2 task 3 
sums: 1 3 6 10 

Reproducible random numbers

A worker seeds its generator when it starts, and the seed comes from the current time and the process identifier, so two runs of a random simulation usually differ. clusterSetRNGStream replaces those seeds with a reproducible set of streams derived from one seed. The generator is the L'Ecuyer combined multiple-recursive one, which is designed for parallel use.

rng.R
library(parallel)
cl <- makeCluster(2)
clusterSetRNGStream(cl, 2026)
draws <- parSapply(cl, 1:4, function(i) round(runif(1), 3))
stopCluster(cl)
cat("draws:", draws, "\n")

The seed 2026 produces the same four draws on every run, as long as the number of workers and the R version stay the same. The assignment of tasks to streams depends on the cluster layout, so changing the number of workers can change the numbers even though the seed does not. For the forking mechanism, the equivalent switch is mc.set.seed = TRUE together with RNGkind("L'Ecuyer-CMRG").

$ Rscript rng.R
draws: 0.195 0.091 0.746 0.872 

A complete example: fitting models in parallel

Parallel work pays off when each task is expensive. Fitting a regression model for every group in a data set is a realistic case. The script splits the iris data by species, sends the three groups to two workers, and fits the same model to each group. The coefficient vectors come back as a list.

models.R
library(parallel)
groups <- split(iris, iris$Species)
cl <- makeCluster(2)
clusterExport(cl, "groups")
fits <- parLapply(cl, groups, function(d) {
  fit <- lm(Sepal.Length ~ Petal.Length, data = d)
  round(coef(fit), 2)
})
stopCluster(cl)
for (name in names(fits)) {
  cat(name, ":", paste(fits[[name]], collapse = " and "), "\n")
}

Each species gets its own intercept and slope, and the printed values are rounded to two decimals before they leave the worker. The split happens in the parent, so the workers only need the groups list and the functions from the stats package. For a larger problem, the same pattern applies to files, simulations, or model specifications: build a list of independent tasks, export what the tasks need, and collect one result per task.

$ Rscript models.R
setosa : 4.21 and 0.54 
versicolor : 2.41 and 0.83 
virginica : 1.06 and 1 

Beyond the parallel package

The two mechanisms above cover most scripts, but two other styles are common. The foreach package with doParallel turns a loop into a parallel loop and is often used with %dopar%. The future package, with future.apply and furrr, separates the code that describes the work from the plan that decides where it runs, so the same script can run sequentially, on local cores, or on a cluster. Both styles eventually call the same operating system facilities as parallel, and both need the same care about exported objects and random seeds.

Parallelism is not a substitute for faster code. A vectorized expression that runs in a fraction of a second is usually better than a parallel loop with the same overhead on every call. Profile first, as the performance article shows, and parallelize the part that still dominates after the single-core code is efficient.

Next steps

The performance and profiling article covers system.time, Rprof, and byte compilation, which measure the work before it is split. The apply family article explains lapply and sapply, the serial functions that mclapply and parSapply replace. The environments article explains why a forked child shares the parent's objects, and the random numbers article covers seeds and generators in a single process.

Source

R manual: the parallel package

R manual: mclapply

R manual: makeCluster

R manual: parLapply and clusterApply

R manual: clusterSetRNGStream

R manual: detectCores

In this article we split independent work over several cores. mclapply forked the current process and returned the same list as lapply, while makeCluster built a socket cluster that works on every platform. clusterExport copied the data to the workers, parLapply and parSapply collected the results, and stopCluster shut the workers down. clusterSetRNGStream made a random simulation reproducible, and the final example fitted one regression per species in parallel. The performance article shows how to find the part of a script that is worth parallelizing in the first place.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.