install.packages(c("future.apply", "data.table", "cluster", "ggplot2"))Parallel Computing and Big Data in R
Friday, November 20: making slow code fast
Friday, Nov 20, 12:10–1:00 PM, Asmundson 242: step by step, on your laptop. Your analysis takes an hour, or your data file takes forever to open. Before you buy a bigger computer, there are four things to try, in this order: find the slow step, vectorize it, run it on all the cores you already have, and read only the data you need. We’ll do each one in R, using this week’s k-means clustering of Colombia’s climate as the example. Bring your laptop.
All the code on this page, in order, is in one script: parallel_big_data.R. Open it in RStudio and run it one section at a time as we go.
About the timings. Every time on this page was measured on a laptop with an Apple M1 Pro chip (10 cores, 16 GB of memory). Your computer will give different numbers, and running the same line twice gives slightly different numbers too. What should match is the pattern: which version is faster, and by roughly how much.
Step 0. Set up
Install the packages once, in the console (skip any you already have):
Then load them and read this week’s data: 3571 grid cells covering Colombia, with longitude, latitude, and the 19 WorldClim climate variables (bio1 to bio19).
library(parallel)
library(future.apply)
library(data.table)
library(cluster)
library(ggplot2)
clim <- read.csv("https://greymonroe.github.io/PLS_206/data/colombia_climate.csv")
str(clim)parallel comes with R, so it never needs installing.
Step 1. Time it first
You can’t speed up code until you know which part is slow. system.time() runs a line and tells you how long it took:
system.time(Sys.sleep(2)) user system elapsed
0.000 0.000 2.005
elapsed is the number you care about: the seconds you sat and waited. (user and system count the time the processor spent working; Sys.sleep() just waits, so they are zero.)
Now time each step of a small clustering analysis:
system.time(clim_scaled <- scale(clim[, 3:21]))
system.time(d <- dist(clim_scaled))
system.time(km <- kmeans(clim_scaled, centers = 6, nstart = 100))
system.time(sil <- silhouette(km$cluster, d))
kmeans() with 100 random starts is the slow step, the bottleneck. Speeding up scale() would save nothing. Always time first, then work on the slowest piece only. (Reading the file was timed from a copy on disk; from the website it also depends on your wifi.)
Step 2. Vectorize before you parallelize
Example: growing degree days, how far each day’s mean temperature is above 10 °C (zero if it’s below). Here are three ways to compute it for a million days, all giving the same answer:
set.seed(1)
temp <- rnorm(1e6, mean = 18, sd = 6) # a million daily temperatures
# 1. for loop
system.time({
gdd_loop <- numeric(length(temp)) # make the empty vector first, then fill it
for (i in seq_along(temp)) {
if (temp[i] > 10) gdd_loop[i] <- temp[i] - 10 else gdd_loop[i] <- 0
}
})
# 2. sapply
system.time(gdd_sapply <- sapply(temp, function(t) if (t > 10) t - 10 else 0))
# 3. vectorized: one function call on the whole vector
system.time(gdd_vec <- pmax(temp - 10, 0))
all.equal(gdd_loop, gdd_vec) # same answer
The vectorized version took 0.007 s: about 25 times faster than the loop and 70 times faster than sapply(). A vectorized function works on the whole vector at once, in compiled code, instead of going back to R for every value. Arithmetic (+, *, log()), comparisons, ifelse(), pmax()/pmin(), rowSums()/colMeans(), and cumsum() are all vectorized. Even 10 cores can’t give you a 25x speed-up, so this step comes first.
Two surprises worth knowing:
- A for loop is not slow in itself. Modern R runs a well-written loop quickly.
sapply()is a loop too, just written differently, and here it was slower. Use the apply family because it’s tidy, not because it’s fast. - Growing a vector is slow. The classic slow loop adds each answer to the end with
c(). Everyc()copies the whole vector, so doubling its length makes it about four times slower:
temp_50k <- temp[1:50000]
system.time({
gdd_grow <- c()
for (t in temp_50k) gdd_grow <- c(gdd_grow, if (t > 10) t - 10 else 0)
})That took 4.8 s for only 50,000 values; the same loop with the empty vector made first took 0.005 s. Make the empty vector first (numeric(n), vector("list", n)), then fill it.
Step 3. The apply family is the bridge to parallel
Some jobs can’t be vectorized: fitting a model many times, once per k, per species, per site, per bootstrap sample. When each fit doesn’t depend on the others, it can run at the same time as the others. That’s the kind of job worth parallelizing.
From Monday’s lecture: to choose the number of clusters k, fit k-means for each k and compare the mean silhouette width. Put one fit in a function:
fit_k <- function(k) {
km <- kmeans(clim_scaled, centers = k, nstart = 100)
sil <- silhouette(km$cluster, dist(clim_scaled))
mean(sil[, "sil_width"])
}
fit_k(3)If you can write your job as lapply(things, function), the parallel version is a one-word change:
future_lapply(), future_sapply(), future_apply() and future_mapply() (from the future.apply package) take the same arguments as lapply(), sapply(), apply() and mapply(), plus future.seed (Step 4).
Step 4. Parallel on your laptop
Your laptop has several cores, each able to run R on its own. Normal R uses one of them. Find out how many you have:
detectCores() # how many cores this computer has
n_workers <- detectCores() - 1 # always leave one free for your computer
n_workersAlways leave at least one core free, so your computer (and RStudio) can still respond while R works.
Now a task that just waits 1 second, run eight times, first one after the other, then in parallel:
slow_task <- function(i) {
Sys.sleep(1)
i^2
}
# Serial: 8 tasks, one after the other
system.time(res_serial <- lapply(1:8, slow_task))
# Parallel: start the workers (separate R sessions in the background)
plan(multisession, workers = n_workers)
nbrOfWorkers()
system.time(res_parallel <- future_lapply(1:8, slow_task))
identical(res_serial, res_parallel) # same answer, in the same order
Each colored box is one task, and the measured start and end of each. Serial: 8.1 s. Parallel: 1.1 s.
What plan(multisession) does. It starts n_workers extra R sessions in the background. future_lapply() sends each one a share of the tasks, plus copies of any functions and data the tasks use, and collects the answers in the original order. Starting the workers took 1.4 s here; you pay that once per plan() call, so call it once near the top of your script. plan(multisession) works the same on Windows, Mac and Linux.
Bootstraps, permutations, simulations and kmeans() all use random numbers. Each worker needs its own stream of random numbers, and you want the whole thing to give the same answer next time. Do both of these:
set.seed(206)
boot_a <- future_sapply(1:5, function(i) mean(sample(clim$bio1, replace = TRUE)),
future.seed = TRUE)
set.seed(206)
boot_b <- future_sapply(1:5, function(i) mean(sample(clim$bio1, replace = TRUE)),
future.seed = TRUE)
identical(boot_a, boot_b) # TRUE: reproducibleWith future.seed = TRUE you get the same answer whatever the number of workers, even with plan(sequential) (no parallel at all). Forget it and you get a warning that starts UNRELIABLE VALUE: One of the 'future.apply' iterations ... unexpectedly generated random numbers without declaring so. Take that warning seriously.
The parallel package that comes with R has mclapply(), which works on Mac and Linux but not on Windows (there it quietly runs on one core). It’s the same idea:
res_mc <- mclapply(1:8, slow_task, mc.cores = n_workers)You’ll see it in older code, including mine. We use future_lapply() here because the same script works on everyone’s computer, and later on a cluster.
Step 5. Choosing k for k-means, serial vs parallel
Back to the real job: fit k = 2 to 12, each with 100 random starts, and score each by its mean silhouette width. Time it serially, then in parallel. Changing only the plan() keeps the code identical, and future.seed = TRUE makes the two runs give exactly the same answer.
ks <- 2:12
# Serial
plan(sequential)
set.seed(206)
t_serial <- system.time(sil_serial <- future_sapply(ks, fit_k, future.seed = TRUE))
t_serial
# Parallel
plan(multisession, workers = n_workers)
set.seed(206)
t_parallel <- system.time(sil_parallel <- future_sapply(ks, fit_k, future.seed = TRUE))
t_parallel
t_serial["elapsed"] / t_parallel["elapsed"] # the speed-up
all.equal(sil_serial, sil_parallel) # same answers
9.8 s serially, 2.7 s with 9 workers: 3.5 times faster, not 9 times. The timeline shows why:
- Uneven jobs. k = 12 takes longer than k = 2. The job is done when the last worker finishes, and here 11 jobs went to 9 workers, so one worker did both k = 11 and k = 12 while the others sat idle.
- Workers slow each other down. Compare the boxes: each fit took longer in parallel than on its own, because the workers share the computer’s memory, and this laptop has 8 fast cores and 2 slower power-saving ones.
- Overhead. Starting workers and copying the data to each of them takes time that the serial version never spends.
Here is the speed-up for different numbers of workers (median of 3 runs each):

The best was 6 workers (3.9x). More workers than that made it slower. That’s normal: test a few values on your own job rather than assuming more is better.
And the answer to the actual question:
sil_k <- data.frame(k = ks, silhouette = sil_parallel)
ggplot(sil_k, aes(x = k, y = silhouette)) +
geom_line() +
geom_point(size = 3) +
scale_x_continuous(breaks = ks) +
labs(x = "Number of clusters (k)", y = "Mean silhouette width") +
theme_classic()
best_k <- ks[which.max(sil_parallel)]
set.seed(206)
km_best <- kmeans(clim_scaled, centers = best_k, nstart = 100)
clim$cluster <- factor(km_best$cluster)
ggplot(clim, aes(x = lon, y = lat, fill = cluster)) +
geom_tile() +
coord_equal() +
labs(x = "Longitude", y = "Latitude", fill = "Climate\ncluster") +
theme_classic()

Silhouette width is highest at k = 2 (0.43): cool mountain cells (mean annual temperature 16 °C, along the Andes) and warm lowland cells (26 °C).
How does the time change with fewer workers? Run the parallel block again with workers = 2, then workers = 4. Which is fastest on your laptop?
for (w in c(2, 4)) {
plan(multisession, workers = w)
set.seed(206)
print(system.time(future_sapply(ks, fit_k, future.seed = TRUE))["elapsed"])
}On the laptop used for this page: 5.4 s with 2 workers and 3.4 s with 4, against 9.2 s serially. Your numbers will differ, but the speed-up should be less than the number of workers.
Bootstrap the correlation between mean annual temperature (bio1) and annual rainfall (bio12): 2000 resamples of the 3571 cells, in parallel, reproducibly. Then time the same thing with plain sapply(). Was parallel worth it?
boot_cor <- function(i) {
rows <- sample(nrow(clim), replace = TRUE)
cor(clim$bio1[rows], clim$bio12[rows])
}
plan(multisession, workers = n_workers)
set.seed(206)
system.time(boot_r <- future_sapply(1:2000, boot_cor, future.seed = TRUE))
quantile(boot_r, c(0.025, 0.975)) # 95% bootstrap interval
set.seed(206)
system.time(boot_r_serial <- sapply(1:2000, boot_cor))Here: 0.13 s in parallel, 0.30 s serially. Parallel was faster, but both are well under a second, less time than starting the workers took (1.4 s). Parallel pays off when the whole job takes minutes, not seconds.
Step 6. Big data: read fast, keep only what you need
First make a big file to practice on: 2 million rows of simulated field-sensor readings (plot, site, date, temperature, rain, soil moisture, NDVI, yield), saved to your computer’s temporary folder. It’s about 100 MB.
set.seed(206)
n <- 2e6
sensors <- data.frame(
plot = sample(1:5000, n, replace = TRUE),
site = sample(c("Davis", "Winters", "Dixon", "Woodland", "Esparto"), n, replace = TRUE),
date = as.Date("2021-01-01") + sample(0:1460, n, replace = TRUE),
temp_c = round(rnorm(n, 18, 6), 2),
rain_mm = round(rexp(n, 1 / 3), 2),
soil_vwc = round(runif(n, 0.05, 0.45), 3),
ndvi = round(runif(n, 0.1, 0.9), 3),
yield_t = round(rnorm(n, 8, 1.5), 2)
)
big_file <- file.path(tempdir(), "sensors.csv")
fwrite(sensors, big_file)
file.size(big_file) / 1e6 # size on disk, in MB
rm(sensors)Read it with fread()
system.time(big_base <- read.csv(big_file))
system.time(big_dt <- fread(big_file))
fread() from data.table read the file about 40 times faster than read.csv() (0.08 s vs 3.3 s). It also uses several cores on its own, with no setup from you. The result is a data.table, which also works as a normal data frame. Its partner fwrite() writes CSVs just as fast.
Check the memory, and keep only the columns you need
format(object.size(big_dt), units = "MB")
big_small <- fread(big_file, select = c("site", "temp_c", "yield_t"))
format(object.size(big_small), units = "MB")
Everything you load sits in your computer’s memory (RAM). Most laptops have 8 to 16 GB, and R needs extra room on top of the data itself while it works, because many steps make copies. Reading only the 3 columns we need cut the memory from 107 MB to 46 MB.
Look first, then work on a sample
# The first 5 rows, without reading the rest
fread(big_file, nrows = 5)
# Work out your code on a random sample, then run it on everything
set.seed(206)
big_sample <- big_dt[sample(.N, 10000)]
big_sample[, .(mean_yield = mean(yield_t)), by = site]Get your code right on 10,000 rows, where every step takes a moment, then run it once on all 2 million. (Don’t use the first rows as your sample: files are often sorted, so the first rows are rarely typical.)
Summarize with data.table
system.time(aggregate(yield_t ~ site, data = big_base, FUN = mean))
system.time(big_dt[, .(mean_yield = mean(yield_t)), by = site])
rm(big_base, big_dt, big_small, big_sample) # free the memory when you're done
invisible(gc())Mean yield per site: 0.48 s with aggregate(), 0.02 s with data.table. (The Oct 16 session covered data.table syntax.)
If a file is bigger than your RAM, no amount of select = will help. Two packages let R work on data that stays on disk, reading only the pieces each step needs:
- arrow: reads Parquet files (a compact, fast alternative to CSV) and lets you filter and summarize with dplyr verbs before anything is loaded into R.
- duckdb: a small database that runs inside R. Point it at CSV or Parquet files and query them with SQL or dplyr.
Neither is needed for this course. If your thesis data heads that way, start with the arrow and duckdb documentation.
Step 7. When your laptop isn’t enough
If a job takes hours on your laptop even after Steps 1 to 6, UC Davis has shared computing clusters (Farm, among others) run by HPC@UCD (documentation: docs.hpc.ucdavis.edu). A cluster is many computers with many cores each. You ask for cores, memory and time, and a scheduler called Slurm runs your job when they’re free.
Jobs like choosing k fit a cluster well as a job array: the same R script runs once per k, each copy as its own job on its own core.

The R script reads which k to fit from the job’s task number:
# fit_k.R: the library() lines, the data and fit_k() from above, then:
k <- as.integer(commandArgs(trailingOnly = TRUE)[1])
result <- fit_k(k)
saveRDS(result, paste0("sil_k", k, ".rds"))And a job script asks Slurm to run it for k = 2 to 12. The general shape:
#!/bin/bash
#SBATCH --job-name=choose-k
#SBATCH --array=2-12
#SBATCH --cpus-per-task=1
#SBATCH --mem=2G
#SBATCH --time=00:30:00
#SBATCH --output=choose-k_%A_%a.out
# plus the --account and --partition lines for your lab's allocation
Rscript fit_k.R $SLURM_ARRAY_TASK_IDAccounts, partitions and how to load R are different for every lab and cluster, so get those from your lab or the HPC@UCD documentation rather than copying them from someone else’s script. Two habits that keep you out of trouble on any cluster: never run heavy computing on the login node (the computer you land on when you log in; submit a job instead), and test on a small piece first, exactly like Step 6.
Troubleshooting
Click a tip to open it.
there is no package called 'future.apply'? Click here
Install it once, in the console: install.packages("future.apply"). It installs future along with it. Then run library(future.apply) again. If it asks “Do you want to install from sources the package which needs compilation?”, say No.
Each task was too small. Starting workers and copying data to them has a fixed cost (1.4 s on the laptop used for this page), so if the whole serial job takes a few seconds, parallel can’t win. Parallelize jobs that take minutes, and make each task a decent chunk of work (one model fit, not one number).
The total size of the ... globals exported ... exceeds the maximum allowed size 500.00 MiB? Click here
Each worker gets its own copy of the data your function uses, and future refuses to copy more than 500 MB per worker unless you say so. First check whether the function really needs the whole object (often a few columns will do; see Step 6). If it does, and you have the memory for one copy per worker, raise the limit, here to 2 GB:
options(future.globals.maxSize = 2 * 1024^3)Every worker is a separate R session holding its own copy of the data, so 9 workers can use 9 times the memory. Use fewer workers (plan(multisession, workers = 2)), or make the data smaller before you start. When you’re done, plan(sequential) shuts the workers down and frees their memory.
The workers talk to your main R session through a connection inside your own computer, which can make Windows ask. Allowing it on private networks is fine. If you cancel, plan(multisession) may hang; restart R (Session → Restart R) and try again.
Put set.seed() right before the future_lapply() / future_sapply() call and add future.seed = TRUE to it (Step 4). kmeans() uses random starts, so it needs both.
The order to try things
- Time it with
system.time(). Find the slow step. - Vectorize that step if you can. Make empty vectors first; never grow them.
- Parallelize independent repeats with
plan(multisession)+future_lapply(..., future.seed = TRUE). Leave a core free. - Read less:
fread(),select =, and a sample while you write the code. - Still too slow? Move it to a cluster, as a job array.
Extra resources
- future.apply: the package we used, with more examples.
- A Future for R: a comprehensive overview: how futures, plans and workers fit together.
- Introduction to data.table:
fread()and fast grouped summaries. - Advanced R: Improving performance: more on vectorizing and profiling.
Back to the full Friday discussion schedule.