Teaching corner · Founding article · Published 2026-11-24 · Open access, CC-BY 4.0

Taking R to its limits: 90+ tips

Michail Tsagris1 · Manos Papadakis2

1 Department of Economics & Institute of Research in Education and Digital Social Sciences and Humanities, University of Crete, Gallos Campus, Rethimno, Greece · orcid 0000-0002-2049-3063 · 2 Independent researcher, Heraklion, Greece

R programmingefficient codestatistical computingvectorizationmemory optimizationnumerical stability
doi: https://doi.org/10.68365/jrepstat.2026.15 Vol. 1 (2026) · Art. 15 Version 1 how to cite ↓ html pdf (typeset)
✓ Reproduced

Reproducibility record

verified 2026-11-13
Result
Reported results reproduced. The code runs end to end on Linux. Every printed comparison keeps its direction, most speed-up factors are smaller than on the authors' laptop.
✓ measured
Entry point
cd code && Rscript R_code.R
✓ executed
Environment
R 4.6.1, Rfast 2.1.5.2, data.table 1.18.6.1, microbenchmark 1.5.0, Matrix 1.7.5, float 0.3.4, matrixStats 1.5.0; rocker/r-ver:4.6.1 on colima, linux/aarch64
✓ measured
Determinism
Two runs byte-identical on Linux aarch64. Timings excluded, they measure the machine.
✓ measured
Archive
taking-r-to-its-limits-90-tips-v1-repro.zip · reviewed bundle SHA-256 194e7784cbead53da72b320ea147e56e76be01ff11d70c61dc9e02398292f1f0 · https://doi.org/10.5281/zenodo.24498832
✓ computed
Data
Open.
declared, route checked
AI use
Language editing, model not stated.
declared

Reproducibility package (.zip, 10 KB) · Zenodo doi:10.5281/zenodo.24498832 · SHA-256 7f0e4f414c71884cfddc967ffbf3a43fa57dc2ceb834cede6fe14f3dd3628dce

$cd code && Rscript R_code.R
Open review

Peer review record

3 rounds · 3 reviewers · signed Full reviewsHide reviews
2026-10-02Major revision2026-10-2210 answers2026-10-22Minor revision2026-11-0916 answers2026-11-14Accepted

The decision letters, the reports the authors read, their answers and the editor's signed decisions, as written. The reports come from the journal's review engine. The authors could have kept this record private until they confirmed the proof.

Round 1Major revision3 reviewers · response
Major revisionConfirmed and signed by Matthias Templ2026-10-02 · orcid 0000-0002-8638-5276
Decision letter2026-10-02A tutorial that compiles more than ninety practical tips for writing faster, lower-memory, and numerically stable R code, aimed at statistical-computing practitioners who run simulations and matrix-heavy analyses and want speed without rewriting in C++. We would be glad to see the revised version.

Thank you for your submission to JRepStat. We are inviting a major revision. The reviewers’ points follow, grouped by weight.

A tutorial that compiles more than ninety practical tips for writing faster, lower-memory, and numerically stable R code, aimed at statistical-computing practitioners who run simulations and matrix-heavy analyses and want speed without rewriting in C++. We would be glad to see the revised version.

How to read this letter. The decision rests on the items marked required. If a required item seems wrong to you, or cannot be done within this paper, say so in your response letter and give the reason. A reasoned decline is a legitimate answer, and the editor weighs it. Reviewers can be mistaken. Items marked recommended or optional are advice from the reviewers. Adopt them, decline them with a sentence, or leave them for later work. None of that counts against the paper. The reviewer reports below carry the same marks. The editor who signs this decision may weigh an item differently in the accompanying message, and that message prevails.

required (the decision rests on these):

  • [consistency-check] The abstract and the introduction both state “more than 100 tips”, but the body contains 94 numbered tips (1 through 94, the last being the [[ versus $ item in Section 11). The title says “90+ tips”, which matches the count. Reconcile the abstract and the two introduction sentences (“a collection of more than 100 tips”, “We have listed more than 100 tips”) with the actual number so the claim agrees with the title and the content.
  • [methods-soundness] Tip 64 states that prcomp() “performs the eigendecomposition of a matrix”. prcomp() computes principal components by singular value decomposition of the (centered) data matrix, while princomp() uses the eigendecomposition of the covariance matrix. Please correct the description so the recommendation and its justification match what the functions do.
  • [Reviewer 1] State the BLAS in use and add a reproducibility script for the reported timings. Several matrix comparisons (crossprod vs t(X) %*% Y, princomp vs prcomp, float throughput) depend on which BLAS is linked, and reference BLAS results can invert under OpenBLAS or MKL. Provide the benchmark script plus sessionInfo and the BLAS identity, or qualify these comparisons as reference-BLAS results.
  • [Reviewer 2] Add a competing-interest statement. The authors maintain Rfast, Rfast2 and estats, which the paper recommends as faster (tips 64, 72, Section 10).
  • [Reviewer 2] Where an authored package is recommended as faster, compare it against the strongest alternative, not base R alone. Either benchmark Rfast/estats functions against matrixStats, collapse and data.table, or soften the superiority claims to “an alternative to base R”.
  • [Reviewer 2] Ship a runnable benchmark script that regenerates the two printed tables (tips 16 and 46) with a fixed seed, the R version, and the BLAS named, or remove the printed numbers. The uploaded file reproduces code chunks but does not run end to end.
  • [Reviewer 2] Correct tip 84: values below .Machine$double.eps (2.22e-16) are not rounded to zero. Underflow to zero happens near 1e-308 (and subnormals to 5e-324). The log.p advice stands, the stated threshold does not.
  • [Reviewer 3] Tip 17 option a3 divides rowsum(x, ina, reorder = FALSE) by as.vector(table(ina)), whose counts are in sorted group order, so the two are misaligned when groups do not first appear in sorted order. Fix the alignment or remove a3.
  • [Reviewer 3] Add data.table coverage beyond fread: keyed joins, grouped aggregation with [, by = ], and update by reference, cross-referenced from tips 12 and 17.
  • [Reviewer 3] A short note on when to leave base R for Rcpp or RcppArmadillo yourself, not only via a wrapper package.

recommended:

  • [methods-soundness] Most matrix timing claims (for example crossprod versus t(X) %*% Y in Tips 52 to 53, princomp versus prcomp in Tip 46, and the float and Matrix tips) depend on the BLAS/LAPACK backend and the platform. Under an optimized multithreaded BLAS several of these gaps shrink or reverse. One sentence stating that the benchmarks were run with the reference BLAS on the described laptop, and that margins vary with the linear algebra backend, would set the reader’s expectations correctly.
  • [methods-soundness] Tip 64 says at most n eigenvalues of the correlation matrix are non-zero when n < p. After centering and standardizing, the rank is at most n - 1, so at most n - 1 eigenvalues are non-zero. Adjust the statement, since the surrounding argument about hd.eigen() rests on this rank.
  • [methods-soundness] Several timing displays (Tips 16 and 46, the profiling output in Tip 2) report microbenchmark or Rprof results, but the data-generating lines and any seed are given only for some. Adding the generating code and a set.seed for each reported benchmark would let a reader reproduce the numbers.
  • [statistical-rigor] Several quantitative speed claims carry no measurement: “at least 10 times faster” for Newton-Raphson versus nlm (tip 77), “3-4 times faster” for the G2 tests (tip 15), “more than 2 times faster” for sum(x %*% m) (tip 54), “almost 2 times faster” for dim over nrow (tip 42), and the many “much faster” statements in Section 10. Either give the timing that supports each figure or state the number as an approximate observation on the authors’ machine.
  • [statistical-rigor] The two benchmark tables (tips 16 and 46) report min, lower quartile, mean, median, upper quartile and max over 20 replications but no reasoning for 20 runs and no statement of the run-to-run spread of the difference. For prcomp versus princomp the maxima (50.55 and 51.37 ms) nearly coincide while the medians differ by about 18 ms, so a reader cannot tell how stable the ordering is. Report the paired difference and its spread, and note that a single laptop with JIT and BLAS settings fixed limits how far the ratios generalise.
  • [writing-quality] In the introduction, “Gillespie and Lovelace (2016) gave a book–length treatment in his book” refers to two authors, so “his” should read “their”. The sentence also repeats “book” three times (Wickham “in his book”, Burns “in his book The R Inferno”, “a book–length treatment in his book”); one pass to vary the wording would read more cleanly.
  • [writing-quality] Tip 80 contains a spelling error, “afraind”, that reads as an author typo rather than an extraction artefact. Please correct to “afraid”.
  • [Reviewer 1] Quantify a representative set of the bare “faster” claims (for example tips 42, 54, 89) with the same benchmark script, so the factors (“almost 2 times”, “more than 2 times faster”, “10-50 times”) are supported.
  • [Reviewer 2] Add collapse (fmean, fsum, fvar) to the grouped-operation tips (17, 38).
  • [Reviewer 3] Note the numerical-stability cost of princomp over prcomp in tip 46, consistent with the paper’s own stability section.
  • [Reviewer 3] Add a note on reproducible parallel RNG (clusterSetRNGStream, mc.set.seed) in Section 9, given the simulation use case the paper motivates.
  • [Reviewer 3] State the counter-case for the micro-optimizations that currently read as absolute (tip 42 dim vs nrow, tip 12 mean accuracy).

optional:

  • [methods-soundness] Tip 46 recommends princomp over prcomp on speed grounds, while the numerical-overflow section stresses stability. princomp via the covariance eigendecomposition is less accurate for ill-conditioned data than the SVD used by prcomp. A short note on when the speed gain is safe would align the two parts of the paper.
  • [statistical-rigor] A comparison across more than one machine, operating system and BLAS backend would show which of the reported ratios are properties of R and which are properties of this particular laptop.

We will correct these in production, and you confirm them in the proof:

  • [consistency-check] The profiling output in Tip 2 lists a function "h" (self.time 0.01) that does not appear in the function f shown just above it. The self-times still sum correctly (8.56 + 0.84 + 0.01 = 9.41), so the total is internally consistent, but the "h" row has no source in the displayed code. Confirm the intended output.
  • [writing-quality] Section 10 has a dropped package name: “The same is true for ordinal logistic regression in and in ordinal (Christensen, 2015)”. A package name is missing before the first “in” (the comparison names only one of the two packages being compared). Please supply the intended package.
  • [Reviewer 1] The R Inferno (Patrick Burns) is cited in the introduction but has no entry in the references. Supply the reference.

Reviews

Report Reviewer 1recommends minorThis is a useful tutorial. The problem is real: R users who run simulations or matrix-heavy analyses routinely leave large speed and memory gains on the table, and a single well-organised list of concrete idioms has clear value for that audience. The coverage is broad and mostly accurate. The numerical-overflow section (tips 79 to 88) is the strongest part. The inverse-logit reformulation, the softplus formula max(x,0) + log1p(exp(-abs(x))), the log-sum-exp trick, working in log-densities, and using log.p for sortable tail probabilities are all correct and are exactly the things practitioners get wrong. The matrix-algebra section is also solid: crossprod/tcrossprod, solve(X, Y) over solve(X) %*% Y, backsolve/forwardsolve for triangular factors, and the associativity point in tip 61 are all sound and well chosen.

Written by the journal's review engine in the role of the application reviewer, and read by the editor before the decision. How the engine works is on the peer review page.

This is a useful tutorial. The problem is real: R users who run simulations or matrix-heavy analyses routinely leave large speed and memory gains on the table, and a single well-organised list of concrete idioms has clear value for that audience. The coverage is broad and mostly accurate. The numerical-overflow section (tips 79 to 88) is the strongest part. The inverse-logit reformulation, the softplus formula max(x,0) + log1p(exp(-abs(x))), the log-sum-exp trick, working in log-densities, and using log.p for sortable tail probabilities are all correct and are exactly the things practitioners get wrong. The matrix-algebra section is also solid: crossprod/tcrossprod, solve(X, Y) over solve(X) %*% Y, backsolve/forwardsolve for triangular factors, and the associativity point in tip 61 are all sound and well chosen.

My main concern as an application reviewer is that many speed claims are asserted without evidence, and the few that carry benchmarks were run on a single laptop with an unstated BLAS. This matters because a good share of the matrix tips are BLAS-bound. Whether crossprod(X, Y) beats t(X) %*% Y, and by how much, and whether princomp beats prcomp, depends on whether R is linked against reference BLAS, OpenBLAS, or MKL. On an optimised multi-threaded BLAS some of these gaps shrink or reverse. Readers will apply these tips on machines unlike yours, so the paper should say which BLAS produced the numbers and should ship the script that produced tables 16 and 46. That also lets the quantified factors scattered through the text (“almost 2 times faster”, “more than 2 times faster”, “10-50 times faster”) be checked. A short reproducibility script with sessionInfo would settle all of this at once and is the natural minimum for a tutorial whose value is its timings.

One consistency point deserves attention because the paper itself raises the standard. Section 7 states that one should not sacrifice numerical stability for speed. Tip 46 then recommends princomp over prcomp on speed grounds alone. princomp works from the covariance matrix and its eigendecomposition, which loses precision relative to the SVD of the centered data that prcomp uses, and the difference shows up on ill-conditioned or nearly collinear data that applied users meet often. A single sentence flagging the tradeoff keeps the tip while honouring the paper’s own principle. A smaller correctness note: tip 36 gives x * (x > 0) for ifelse(x > 0, x, 0), which differs in the presence of NA, and tip 87’s integer point is right and could add that length/dim/nrow return integers so n * n overflows silently, which the example already shows.

The headline count needs fixing. The abstract and introduction say “more than 100” tips, the title says “90+”, and the list runs to 94. The claim that this is the first compilation of such length depends on getting that number straight, so please set it to what the paper actually contains. The R Inferno is discussed in the introduction but is absent from the references and should be added. On presentation, the tips read as a flat sequence within each section, and a few (38 on apply for medians, 48 on by) qualify their own advice in ways that could confuse a reader skimming for a rule. A one-line summary table grouping the tips by theme would help the tutorial’s usability, though the paper stands without it.

Numbered suggestions to the authors:

  1. required Set the tip count consistently across the title, abstract, and introduction to the number actually present (94 by my count), since the “first such list” claim rests on it.

  2. required State the BLAS used for the benchmarks and provide the script plus sessionInfo that produced the timing tables (tips 16 and 46). Note that crossprod vs explicit transpose-multiply, princomp vs prcomp, and the float throughput claim are BLAS-dependent and can narrow or invert under OpenBLAS or MKL, so present them as reference-BLAS results or qualify them.

  3. required Add one sentence to tip 46 noting that princomp is less numerically stable than prcomp because it eigendecomposes the covariance matrix, so the speed gain trades against precision on ill-conditioned data.

  4. [editor_fix] Add a references entry for The R Inferno (P. Burns), which is cited in the introduction but missing from the reference list.

  5. recommended Support the unquantified speed factors for a representative subset (for example tips 42, 54, and 89) using the same benchmark script, so the stated multipliers are backed by numbers.

  6. recommended Note in tip 36 that x * (x > 0) and ifelse(x > 0, x, 0) differ when x contains NA, so readers do not swap them blindly.

  7. optional A short table grouping the tips by theme (memory, vectorization, matrix algebra, numerical stability) would make the tutorial easier to navigate and reference.

Report Reviewer 2recommends majorThis is a tutorial, and I review it as one. A curated list of idioms does not owe a benchmark for every line the way a methods paper owes one for its headline result. The numerical-overflow section (tips 79 to 88) is the strongest part: the inverse-logit reformulation, the softplus identity max(x,0)+log1p(exp(-|x|)), the log-sum-exp shift, log1p and expm1, and working with log-densities are all correct and well chosen. The vectorization and preallocation advice is sound and the worked profiling example makes its point cleanly.

Written by the journal's review engine in the role of the methodology reviewer, and read by the editor before the decision. How the engine works is on the peer review page.

This is a tutorial, and I review it as one. A curated list of idioms does not owe a benchmark for every line the way a methods paper owes one for its headline result. The numerical-overflow section (tips 79 to 88) is the strongest part: the inverse-logit reformulation, the softplus identity max(x,0)+log1p(exp(-|x|)), the log-sum-exp shift, log1p and expm1, and working with log-densities are all correct and well chosen. The vectorization and preallocation advice is sound and the worked profiling example makes its point cleanly.

My concerns are methodological and they cluster. First, the paper is written by the maintainers of Rfast, Rfast2 and estats, and it recommends those packages as faster (tips 64 and 72, and Section 10). There is no competing-interest statement, and that needs to be added. Tied to it is a fairness question that runs through the paper. Many tips present a fast option against the slowest baseline only. Where the recommended option is an authored package, the relevant comparison is against the strongest alternative in the ecosystem, which for column medians, variances and distances means matrixStats, collapse and data.table, and for a truncated eigendecomposition (tip 64) means something like RSpectra or irlba. Please either benchmark against those or phrase the recommendation as an alternative to base R. I have marked the comparison required with the softening as the low-cost route.

Second, reproducibility of the numbers you print. The paper shows two benchmark tables (centering in tip 16, princomp against prcomp in tip 46) and asserts ratios elsewhere (“more than 2 times faster”, “almost 2 times faster”). None of the matrix timings can be read without the BLAS, since reference BLAS, OpenBLAS and MKL change the relative cost of crossprod, solve, eigen and the float tip (70) by large factors. The environment gives the R version but not the BLAS, and the code file cannot regenerate the two tables because several chunks depend on objects defined only in the prose. A single script that builds the inputs, sets a seed, runs microbenchmark or bench, and prints the two tables would close this, or the printed numbers could be removed and the claims kept qualitative.

Third, two technical corrections. Tip 84 states that p-values below .Machine$double.eps are rounded to zero. That is off by roughly 290 orders of magnitude. A p-value of 1e-100 is representable and sortable. Underflow to zero happens near the smallest normal double, about 1e-308, with subnormals below that. The advice to carry log p-values is good, so only the justification needs fixing. Tip 46 recommends princomp over prcomp for speed. princomp forms and diagonalises the covariance matrix, which is the less stable route, while prcomp uses the SVD of the centered data. In a paper whose own motto is not to trade stability for speed, that recommendation needs one sentence of caveat. In the same spirit, tip 12 recommends sum(x)/length(x) over mean for speed, and mean’s extra cost buys the two-pass accuracy you are giving up, which is worth a half-sentence.

A lighter point on the many micro-claims. “nrow is almost 2 times faster than dim(X)[1]” (tip 42), the internal .colSums (tip 39), iterating over elements (tip 93): these are true as ratios and negligible as absolute times. A reader can spend real effort chasing nanoseconds. Where you give a ratio without a measurement, either measure it or mark it as a constant-factor nicety.

Numbered suggestions to the authors:

  1. required Add a competing-interest statement naming Rfast, Rfast2 and estats as packages the authors maintain, since the paper recommends them (tips 64, 72, Section 10).
  2. required For each authored-package recommendation, compare against the strongest alternative (matrixStats, collapse, data.table, and RSpectra or irlba for tip 64), or reword the claim to “an alternative to base R” where you do not benchmark.
  3. required Supply a runnable script that regenerates the tables in tips 16 and 46 with a fixed seed, the R version, and the BLAS stated, or remove the printed timings and keep the claims qualitative.
  4. required In tip 84, replace the .Machine$double.eps threshold with the correct underflow behaviour near 1e-308 and the subnormal range, keeping the log.p recommendation.
  5. required Add one sentence to tip 46 that princomp diagonalises the covariance matrix and is less stable than the SVD-based prcomp, so the speed gain carries an accuracy cost.
  6. [editor_fix] Make the tip count consistent: the abstract says “more than 100”, the title says “90+”, and the list ends at 94.
  7. recommended Add collapse (fmean, fsum, fvar) to the grouped-operation tips 17 and 38, where it is typically faster than rowsum and aggregate.
  8. recommended Temper the unquantified ratio claims (tips 42, 54, 70, 93) to qualitative statements, or back each with a measurement, and add a half-sentence to tip 12 on the accuracy that sum/length gives up relative to mean.
  9. optional A table of the matrix-tip speedups under reference BLAS, OpenBLAS and MKL would settle how much each recommendation depends on the linear algebra backend.
Report Reviewer 3recommends minorI read this as a software and reproducibility reviewer, with the uploaded R file treated as part of the submission. The tutorial is useful and most of the advice is correct and well chosen. The matrix-algebra tips (crossprod, solve(X, Y), backsolve, the Mahalanobis route to the multivariate normal exponent) and the numerical-overflow section (log-sum-exp, log1p, log-densities, log p-values) are the strongest parts and are the kind of thing many R users genuinely do not know. My concerns are about whether the shipped artifact does what the submission record says it does, one correctness bug, and a disclosure that a computing venue expects.

Written by the journal's review engine in the role of the software reviewer, and read by the editor before the decision. How the engine works is on the peer review page.

I read this as a software and reproducibility reviewer, with the uploaded R file treated as part of the submission. The tutorial is useful and most of the advice is correct and well chosen. The matrix-algebra tips (crossprod, solve(X, Y), backsolve, the Mahalanobis route to the multivariate normal exponent) and the numerical-overflow section (log-sum-exp, log1p, log-densities, log p-values) are the strongest parts and are the kind of thing many R users genuinely do not know. My concerns are about whether the shipped artifact does what the submission record says it does, one correctness bug, and a disclosure that a computing venue expects.

The declared entry point is Rscript R code.R, which signals a runnable artifact. It is not one. The file’s own header states that several fragments refer to objects defined only in surrounding prose, and a top-to-bottom run fails early: chunk 2 calls microbenchmark(mean(x), ...) with no x defined, chunk 5 uses n, chunk 6 uses fast and slow, and so on. No set.seed appears anywhere, so even the self-contained chunks that build data with rnorm do not reproduce fixed numbers. The two timing tables in the paper (centering in tip 16, princomp against prcomp in tip 46) are pasted into the code as comments and are not regenerated by any runnable, seeded code. The machine is named, which is good provenance, but timings also depend on the BLAS, the OS and the R build, none of which is pinned beyond the prose. For a paper whose entire value rests on speed claims, a reader should be able to run something and see the numbers appear. The cheapest honest fix is to split the file: keep the illustrative snippets as clearly non-executable, and add two or three small seeded scripts that build the inputs and print the benchmark tables. If the file is meant to be snippets only, the declared entry point should say so.

Tip 17 has a correctness bug in its “a bit faster” variant. rowsum(x, ina, reorder = FALSE) returns group rows in order of first appearance, while as.vector(table(ina)) returns counts in sorted factor-level order. When the two orders differ, each group mean is divided by another group’s count. The default rowsum(x, ina) in a2 is fine because it sorts. Please either align the counts to the reorder = FALSE order or drop a3. This belongs in a tutorial precisely because a reader will copy it.

The authors maintain Rfast, Rfast2 and estats, and the paper recommends these packages in tips 64, 72 and 74 and across Sections 9 and 10. A reader is entitled to know that. Please add a short interest declaration. This is not a judgement on the recommendations, several of which are reasonable, only on disclosing who wrote the packages being recommended.

Two smaller content points are worth lining up with the paper’s own stated priorities. Section 7 argues that numerical stability should not be sacrificed for speed, yet tip 46 recommends princomp over prcomp purely on timing. princomp forms the covariance and eigendecomposes it, which is less accurate for near-collinear data than the SVD route in prcomp, and one sentence should say so. On data.table, the paper uses it only through fread. For the aggregation tips (12 and 17) and for large grouped work generally, [, by = ], keyed joins and update by reference are often the fastest route available, and a tutorial on efficient R aimed at large data reads as incomplete without them. The tip count in the abstract and introduction (“more than 100”) does not match the 94 numbered tips or the “90+” in the title.

Numbered suggestions to the authors:

  1. required Make R code.R run end to end with inputs defined and set.seed set, or re-declare it as non-executable snippets and add separate seeded scripts that regenerate the centering (tip 16) and princomp/prcomp (tip 46) tables.
  2. required Fix tip 17: align rowsum(x, ina, reorder = FALSE) with counts in the same order, or remove the a3 variant, because dividing by as.vector(table(ina)) uses sorted-order counts.
  3. required Add a declaration of the authors’ interest in Rfast, Rfast2 and estats where those packages are recommended.
  4. [editor_fix] Reconcile the tip count: abstract and introduction say “more than 100”, the list ends at 94, and the title says “90+”.
  5. recommended Add data.table beyond fread: keyed joins, grouped aggregation with [, by = ], and update by reference, linked from tips 12 and 17.
  6. recommended In tip 46, state that princomp is less accurate than prcomp for near-collinear data.
  7. recommended In Section 9, add a note on reproducible parallel RNG using clusterSetRNGStream and mc.set.seed.
  8. recommended Give the counter-case for the micro-optimizations that read as absolute, including tip 42 (dim vs nrow) and the accuracy cost in tip 12 (mean vs sum(x)/length(x)).
  9. optional Add a short note on when to move to Rcpp or RcppArmadillo yourself, as a complement to the wrapper-package route.

Revision

Authors' response2026-10-22 · 10 answersAuthors confirm each required point as done or give their reason for declining it. Further answers are voluntary, because the review compares every revision with the previous version and the next round's reports say what remains open.

Authors confirm each required point as done or give their reason for declining it. Further answers are voluntary, because the review compares every revision with the previous version and the next round's reports say what remains open.

We thank the reviewers for their time. We have addressed most of their comments. We further proof read the paper and corrected more typos, re-organized some parts, and deleted a few tips, we are now counting 91 tips. There is a comment though that we must ask. The reviewers ask us to write add a competing-interest statement since we are he maintainers of Rfast, Rfast2 and estats R packages and we mention these in the paper. Do we have to add this statement? If yes, can you please help us write it?

required The abstract and the introduction both state "more than 100 tips", but the body contains 94 numbered tips (1 through 94, the last being the `[[` versus `$` item in Section 11). The title says "90+ tips", which matches the count. Reconcile the abstract and the two introduction sentences ("a collection of more than 100 tips", "We have listed more than 100 tips") with the actual number so the claim agrees with the title and the content.
Done
required Tip 64 states that prcomp() "performs the eigendecomposition of a matrix". prcomp() computes principal components by singular value decomposition of the (centered) data matrix, while princomp() uses the eigendecomposition of the covariance matrix. Please correct the description so the recommendation and its justification match what the functions do.
Done
required State the BLAS in use and add a reproducibility script for the reported timings. Several matrix comparisons (crossprod vs t(X) %*% Y, princomp vs prcomp, float throughput) depend on which BLAS is linked, and reference BLAS results can invert under OpenBLAS or MKL. Provide the benchmark script plus sessionInfo and the BLAS identity, or qualify these comparisons as reference-BLAS results.
Done
required Add a competing-interest statement. The authors maintain Rfast, Rfast2 and estats, which the paper recommends as faster (tips 64, 72, Section 10).
Done
required Where an authored package is recommended as faster, compare it against the strongest alternative, not base R alone. Either benchmark Rfast/estats functions against matrixStats, collapse and data.table, or soften the superiority claims to "an alternative to base R".
Done
required Ship a runnable benchmark script that regenerates the two printed tables (tips 16 and 46) with a fixed seed, the R version, and the BLAS named, or remove the printed numbers. The uploaded file reproduces code chunks but does not run end to end.
Done
required Correct tip 84: values below .Machine$double.eps (2.22e-16) are not rounded to zero. Underflow to zero happens near 1e-308 (and subnormals to 5e-324). The log.p advice stands, the stated threshold does not.
Done
required Tip 17 option a3 divides `rowsum(x, ina, reorder = FALSE)` by `as.vector(table(ina))`, whose counts are in sorted group order, so the two are misaligned when groups do not first appear in sorted order. Fix the alignment or remove a3.
Done
required Add data.table coverage beyond `fread`: keyed joins, grouped aggregation with `[, by = ]`, and update by reference, cross-referenced from tips 12 and 17.
Done
required A short note on when to leave base R for Rcpp or RcppArmadillo yourself, not only via a wrapper package.
Done

The authors' full response letter (PDF)

Round 2Minor revision3 reviewers · response
Minor revisionConfirmed and signed by Matthias Templ2026-10-22 · orcid 0000-0002-8638-5276

The editor's note

Confirm of the draft. Eight required points remain, four of them carried over from round 1. The editor intends this to be the last round and accepts the lighter routes the letter offers for the benchmark points.

Decision letter2026-10-22A tutorial compiling 91 practical tips for writing faster, lower-memory, and numerically stable R code, aimed at statistical-computing practitioners who run simulations and matrix-heavy analyses and want speed without rewriting in C++. We would be glad to see the revised version.

Thank you for the revised version of your manuscript. This is round 2, and we are inviting a further minor revision. Because you were asked for a major revision, this round read the new version whole, and the editor has read your response against it. What follows is our reading of this version. An item carried over from the previous round says so.

A tutorial compiling 91 practical tips for writing faster, lower-memory, and numerically stable R code, aimed at statistical-computing practitioners who run simulations and matrix-heavy analyses and want speed without rewriting in C++. We would be glad to see the revised version.

How to read this letter. The decision rests on the items marked required. If a required item seems wrong to you, or cannot be done within this paper, decline it on the revision page and give the reason. A reasoned decline is a legitimate answer, and the editor weighs it. Reviewers can be mistaken. Items marked recommended or optional are advice from the reviewers. Adopt them, decline them with a sentence, or leave them for later work. None of that counts against the paper. The reviewer reports below carry the same marks. The editor who signs this decision may weigh an item differently in the accompanying message, and that message prevails.

required (the decision rests on these):

  • [novelty-and-prior-art] The nearest prior work is the authors’ own earlier preprint “Taking R to its limits: 70+ tips” (Tsagris and Papadakis, 2018, PeerJ Preprints, doi:10.7287/peerj.preprints.26605v1), which the search found and which does not appear in the reference list. The current manuscript states “to the best of our knowledge, this is the first time such a long list has been compiled in one place,” and the response letter itself refers to “an earlier version of this paper, which can be found on the web.” That earlier version already compiled a comparable list, so the first-compilation claim is not accurate as written without citing and positioning against it. Please cite the 2018 preprint and state what the present version adds relative to it (the count moving from 70+ to 91, the numerical-stability section, the data.table and matrix additions), or qualify the first-compilation sentence.
  • [theory-and-proofs] Tip 17 option a3 still misaligns in the same family of cases the prior round flagged. The author removed reorder = FALSE, so rowsum(x, ina) now returns groups in sorted order and divides by as.vector(tabulate(ina)). This agrees only when the group codes are the consecutive positive integers 1..k. When the codes have a gap, say ina = c(1,3,3,1), rowsum returns two rows while tabulate(ina) returns c(2,0,2) of length three, and the division recycles, so each group mean is divided by the wrong count. Option a2 with table(ina) is safe because table returns only present levels in sorted order. Either drop a3, or add the “consecutive strictly positive integers” caveat that Tip 16 already states for tabulate and cross-reference it.
  • [ethics-and-integrity] The manuscript still carries no competing-interest statement. The authors maintain Rfast, Rfast2 and estats, and the paper recommends these packages as faster in tips 62 (hd.eigen), 70 (Rfast::Dist), 72 (colMedians) and across Sections 9 and 10. Three reviewers asked for this in the prior round, and the response letter defers it (“We will ask the editors what to write and where”) rather than adding it. The disclosure is required regardless of how the recommendations are judged. Add a short statement naming Rfast, Rfast2 and estats as packages the authors maintain, placed before the references. A usable form: “M. Tsagris and M. Papadakis are the maintainers of the R packages Rfast, Rfast2 and estats, which are recommended in this paper. The authors declare no other competing interests.”
  • [Reviewer 2] Add the competing-interest statement. It is still absent from the manuscript, and the paper recommends Rfast, Rfast2, estats and hd.eigen. A one-line declaration suffices and I give wording below.
  • [Reviewer 1] State the BLAS in use and add a reproducibility script for the reported timings. Several matrix comparisons (crossprod vs t(X) %*% Y, princomp vs prcomp, float throughput) depend on which BLAS is linked, and reference BLAS results can invert under OpenBLAS or MKL. Provide the benchmark script plus sessionInfo and the BLAS identity, or qualify these comparisons as reference-BLAS results. This was asked in the previous round and is still open.
  • [Reviewer 2] Where an authored package is recommended as faster, compare it against the strongest alternative, not base R alone. Either benchmark Rfast/estats functions against matrixStats, collapse and data.table, or soften the superiority claims to “an alternative to base R”. This was asked in the previous round and is still open.
  • [Reviewer 2] Ship a runnable benchmark script that regenerates the two printed tables (tips 16 and 46) with a fixed seed, the R version, and the BLAS named, or remove the printed numbers. The uploaded file reproduces code chunks but does not run end to end. This was asked in the previous round and is still open.
  • [Reviewer 3] Add data.table coverage beyond fread: keyed joins, grouped aggregation with [, by = ], and update by reference, cross-referenced from tips 12 and 17. This was asked in the previous round and is still open.

recommended:

  • [methods-soundness] The matrix-timing recommendations (crossprod versus t(X) %*% Y in tips 50 to 51, princomp versus prcomp in tip 44, the float tip 68) are presented as general orderings, and the authors’ own response notes they have previously seen prcomp run faster than princomp on other hardware. The revision adds the LAPACK version (3.12.1) in the introduction but not the BLAS identity, nor the one sentence that these margins depend on the linear algebra backend and can narrow or reverse under an optimized multithreaded BLAS. Adding that sentence would make the printed orderings match what they are, observations under one backend. This partially addresses d78ce440.
  • [statistical-rigor] The paper’s quantitative speed multipliers are still stated as bare factors with no measurement behind them: “3-4 times faster” (tip 14), “at least 10 times faster” (tip 75), “more than 2 times faster” (tip 52), “almost 2 times faster” (tip 40), “10-50 times faster” (tip 86). The author declined to quantify these, citing variation between their own machines, and added a general caveat to the introduction naming the laptop and LAPACK version. That caveat helps, but the specific numbers still read as measured ratios rather than impressions. Replace each precise multiplier with an approximate form (for example “roughly twice as fast on our laptop”) so the figure matches the evidence the authors say they have.
  • [statistical-rigor] The two benchmark tables (tip 15 centering, tip 44 princomp vs prcomp) report six order statistics over 20 replications, with no paired difference between methods and no basis given for 20 runs. For princomp vs prcomp the medians differ by about 18 ms while the maxima nearly coincide (50.55 vs 51.37 ms), so a reader cannot judge how stable the ordering is. The author declined, preferring to present the output as the timing packages produce it. Report the paired difference and its spread for these two comparisons, and state that a single laptop with fixed JIT and BLAS settings limits how far the ratios carry.
  • [prose-and-style] The introduction stacks three second-clause-after-comma sentences in the car/jeep paragraph (“One might observe …”, “Differences from 40 seconds …”, “Sometimes one tip saves …”); a reader skimming for the rule would be helped by tightening, though the passage is clear as written.
  • [Reviewer 1] Phrase the bare ratio claims (tips 14, 40, 52, 75, 86) as observations on the authors’ Windows laptop, consistent with the authors’ own statement that the factors vary across machines.
  • [Reviewer 3] Name the BLAS in the paper text, not only LAPACK 3.12.1, since the matrix timings depend on it.
  • [Reviewer 3] The reproducible parallel RNG note (Section 9) is still absent. The decline rests on timing, but the point is reproducibility of simulation results.
  • [methods-soundness] Several timing displays (Tips 16 and 46, the profiling output in Tip 2) report microbenchmark or Rprof results, but the data-generating lines and any seed are given only for some. Adding the generating code and a set.seed for each reported benchmark would let a reader reproduce the numbers. This was asked in the previous round and is still open.
  • [Reviewer 2] Add collapse (fmean, fsum, fvar) to the grouped-operation tips (17, 38). This was asked in the previous round and is still open.
  • [Reviewer 3] State the counter-case for the micro-optimizations that currently read as absolute (tip 42 dim vs nrow, tip 12 mean accuracy). This was asked in the previous round and is still open.

optional:

  • [statistical-rigor] A cross-machine, cross-BLAS comparison would separate ratios that are properties of R from ratios that are properties of this laptop. The author declined on scope grounds and notes that on an earlier machine prcomp was faster than princomp, which itself shows the ratios are not stable. A multi-platform table would settle which recommendations are backend-dependent, and can sit in a later paper.

We will correct these in production, and you confirm them in the proof:

  • [writing-quality] Tip 17: “Note that thus command works also for matrices” should read “this command”. The correct word is determined by the sentence, so this leaves the author’s list and enters the proof.
  • [writing-quality] Tip 19 (incremental calculations): “the first–rder partial correlations” is missing a letter and reads as “first-order”. Confirm in the proof.

Reviews

Report Reviewer 1recommends minorOf the three required points and two lighter ones I raised, the tip count is reconciled (abstract, title and the list at 91 now agree), the R Inferno reference is supplied, tip 44 carries the princomp stability footnote, and tip 34 notes the NA difference between x * (x > 0) and ifelse. The content remains strong, and the numerical-overflow section (tips 77 to 85) is still the best part of the paper. The tip-17 rowsum alignment and the tip-82 underflow threshold, both raised by other reviewers, now read correctly.

Written by the journal's review engine in the role of the application reviewer, and read by the editor before the decision. How the engine works is on the peer review page.

Of the three required points and two lighter ones I raised, the tip count is reconciled (abstract, title and the list at 91 now agree), the R Inferno reference is supplied, tip 44 carries the princomp stability footnote, and tip 34 notes the NA difference between x * (x > 0) and ifelse. The content remains strong, and the numerical-overflow section (tips 77 to 85) is still the best part of the paper. The tip-17 rowsum alignment and the tip-82 underflow threshold, both raised by other reviewers, now read correctly.

Two things my prior report asked for are only partly settled. I asked for the BLAS to be stated and for the matrix comparisons to be qualified as backend-dependent. The authors added “The LAPACK version is 3.12.1” to the introduction and state that sessionInfo() is shipped with the code. LAPACK is not the BLAS, and the BLAS is what governs the relative cost of crossprod, solve, eigen, princomp and the float throughput tip. sessionInfo() does report the BLAS, so a reader who opens the script can find it, and the reproducibility minimum is therefore in hand. What is still missing is the one sentence that warns the reader of the paper, who never opens the script, that several definite orderings in Section 5 can shrink or invert on an optimised multi-threaded BLAS. The authors themselves note in their reply that on a different machine they once saw prcomp beat princomp, which is exactly the caveat that belongs in the text. I have marked this recommended because the shipped environment covers the verifiable minimum.

On the bare speed ratios (tips 14, 40, 52, 75, 86), the authors decline to quantify and explain that the factors differ between their own laptop and desktop. That is a reasonable decline for a tutorial of idioms. The cheap step that remains is to attach “on our machine” to these figures, which matches the authors’ own account and costs nothing in content. Recommended.

The one point that still needs an action is the competing-interest statement. The paper recommends Rfast, Rfast2 and estats, which the authors maintain, and no declaration appears. The authors have asked the editor whether it is required and for help wording it. It is required, and placement is for the editor to confirm, so one workable form is: “M. Tsagris and M. Papadakis are the authors and maintainers of the R packages Rfast, Rfast2 and estats, which are recommended in this paper.” This is new to my report, it was raised by two other reviewers, and it is the kind of point that holds a paper for one short exchange rather than another full round.

Numbered suggestions to the authors:

  1. required Add a competing-interest statement naming Rfast, Rfast2 and estats as packages the authors maintain. A workable sentence: “M. Tsagris and M. Papadakis are the authors and maintainers of the R packages Rfast, Rfast2 and estats, which are recommended in this paper.” The editor will confirm placement.

  2. recommended Add one sentence to the introduction or Section 5 that the matrix comparisons were run with the BLAS on the described laptop, and that the margins for crossprod versus explicit transpose-multiply, princomp versus prcomp, and the float tip can narrow or reverse under OpenBLAS or MKL.

  3. recommended Mark the bare ratio claims in tips 14, 40, 52, 75 and 86 as observations on the authors’ Windows laptop, since the replies state the factors vary by machine.

Report Reviewer 2recommends minorOf the five required points and the lighter ones I raised, all but one are met, and the one that remains is the cheapest of the set. Tip 84 now describes underflow near 1e-308 with the subnormal range (tip 82 in the new numbering), the princomp stability cost is stated as a footnote to the matrix-PCA tip, the prcomp description now says singular value decomposition of the centered data, the n-1 rank statement for hd.eigen is corrected, and the tip count reads 91 consistently across the title, abstract and introduction. The accuracy cost of sum(x)/length(x) against mean is now in the text. The authored-package comparisons are framed in the introduction as comparisons against R’s built-in functions, which is the softening route I offered, and I am satisfied with it. Section 10 adds matrixStats and collapse as complementary collections, which is a fair acknowledgement.

Written by the journal's review engine in the role of the methodology reviewer, and read by the editor before the decision. How the engine works is on the peer review page.

Of the five required points and the lighter ones I raised, all but one are met, and the one that remains is the cheapest of the set. Tip 84 now describes underflow near 1e-308 with the subnormal range (tip 82 in the new numbering), the princomp stability cost is stated as a footnote to the matrix-PCA tip, the prcomp description now says singular value decomposition of the centered data, the n-1 rank statement for hd.eigen is corrected, and the tip count reads 91 consistently across the title, abstract and introduction. The accuracy cost of sum(x)/length(x) against mean is now in the text. The authored-package comparisons are framed in the introduction as comparisons against R’s built-in functions, which is the softening route I offered, and I am satisfied with it. Section 10 adds matrixStats and collapse as complementary collections, which is a fair acknowledgement.

One required point is genuinely open. The competing-interest statement is still not in the manuscript. The author’s reply asks the editor what to write and where, which is a reasonable process question, so I will answer it here rather than leave it hanging. The venue expects a short declaration wherever authors recommend packages they maintain, and the paper recommends Rfast, Rfast2, estats and hd.eigen in tips 62, 70, 72 and across Sections 9 and 10. A single sentence placed before the references settles it, for example: “The authors maintain the R packages Rfast, Rfast2 and estats, which are among the packages discussed in this paper.” This is not a judgement on the recommendations, several of which are reasonable, only a disclosure of who wrote them.

The second required item is new in this version and I flag it as such. The author fixed the original tip 17 alignment problem for variant a2 by letting rowsum sort the groups, which is correct. Variant a3 then divides by as.vector(tabulate(ina)). tabulate returns one entry per integer position from 1 upward and inserts a zero for any absent code, so for a grouping like ina with values 1, 3, 4 it returns a length-4 vector while rowsum returns three rows. The division then recycles and misaligns silently. Tip 16 already warns that tabulate needs consecutive strictly positive values, and the same condition governs a3. A reader will copy this line, so either carry that condition into tip 17 or drop a3 and keep a2.

On reproducibility, the uploaded script now opens with sessionInfo and the environment is documented, and the declined seed is a reasonable call for a measurement of timing. The remaining gap is small. The introduction names the LAPACK version, which is a different library from the BLAS that drives crossprod, eigen and the float throughput tip. On default Windows R this is the reference BLAS, so one sentence saying the timings are reference-BLAS results on the described laptop and that the margins change under OpenBLAS or MKL would set reader expectations correctly. I have kept this recommended because the environment is now stated and a reader can reconstruct it.

Numbered suggestions to the authors:

  1. required Add a competing-interest statement before the references naming Rfast, Rfast2 and estats as packages the authors maintain, since the paper recommends them (tips 62, 70, 72, Sections 9 and 10). Suggested wording: “The authors maintain the R packages Rfast, Rfast2 and estats, which are among the packages discussed in this paper.”

  2. required In tip 17, either add the condition that ina must be consecutive strictly positive integers for the a3 variant, or remove a3, because as.vector(tabulate(ina)) misaligns with rowsum(x, ina) when group codes are non-consecutive. This issue is new in this version.

  3. recommended Add one sentence to the introduction stating that the printed timings are reference-BLAS results on the described Windows laptop and that the margins vary with the linear algebra backend, since the stated LAPACK version does not fix the BLAS that governs the matrix tips.

Report Reviewer 3recommends minorOf the three required points and six lighter ones I raised, two of the three required are met and one is still open.

Written by the journal's review engine in the role of the software reviewer, and read by the editor before the decision. How the engine works is on the peer review page.

Of the three required points and six lighter ones I raised, two of the three required are met and one is still open.

The tip 17 correctness bug is fixed. The a3 variant now reads rowsum(x, ina) / as.vector(tabulate(ina)), and the default rowsum sorts numeric group labels numerically, so for the consecutive positive-integer grouping that tabulate needs anyway the rows and counts line up. The tip count is now consistent across the title, abstract and introduction at 91, and the numbered list runs 1 to 91. The p-value underflow threshold in tip 82 is corrected to near 1e-308 with the subnormal range noted, the hd.eigen rank in tip 62 reads n-1, the princomp footnote in tip 44 states the SVD-versus-covariance accuracy cost, and tip 11 now states that mean makes two passes in extended precision. The data.table material in tip 17 adds grouped aggregation by reference, which covers the main gap I flagged. These all read correctly.

The competing-interest statement is the one required point that remains open. The paper recommends Rfast, Rfast2 and estats (tips 62, 70, 72 and Section 10), which the authors maintain, and there is no disclosure anywhere in the revised text. The authors deferred to the editor and asked for wording, which is a reasonable request, so a draft is in suggestion 1. This is a disclosure the venue expects when an authored package is recommended as faster, and it stays required until it appears in the manuscript.

On the reproducibility points I accept most of the reasoned declines. For timing comparisons a fixed seed genuinely does not matter, and the two printed tables (tip 15 centering, tip 44 princomp) can be reconstructed from the stated dimensions (10,000 by 20 and 10,000 by 50). Adding sessionInfo() at the top of the uploaded code is good provenance, since running it prints the linked BLAS and LAPACK. One gap stays worth a sentence. The intro names LAPACK 3.12.1, but the matrix timings (crossprod against explicit transpose-multiply, princomp against prcomp, the float tip) depend on the BLAS, which reference, OpenBLAS and MKL change by large factors. Naming the BLAS in the text, not only in the code, sets reader expectations. The parallel RNG note I asked for is still absent. The decline again rests on timing, but Section 9 motivates simulation studies, and a reader who parallelises one will want reproducible streams for the results, not the timings. It stays a recommendation and does not hold the paper.

Numbered suggestions to the authors:

  1. required Add a competing-interest statement. A suitable form: “M. Tsagris and M. Papadakis are the authors and maintainers of the R packages Rfast, Rfast2 and estats, which are recommended in this tutorial. These packages are free and open source and the authors derive no financial benefit from them.” Place it as a short section before the references or in a footnote on first mention.
  2. recommended State the BLAS used for the benchmarks in the paper text, since the matrix timings in tips 44, 50 to 52 and 68 narrow or invert under OpenBLAS or MKL, and LAPACK 3.12.1 alone does not identify it.
  3. recommended In Section 9, add a note on reproducible parallel RNG using clusterSetRNGStream and mc.set.seed, aimed at reproducing simulation results rather than timings.

Revision

Authors' response2026-11-09 · 16 answersAuthors confirm each required point as done or give their reason for declining it. Further answers are voluntary, because the review compares every revision with the previous version and the next round's reports say what remains open.

Authors confirm each required point as done or give their reason for declining it. Further answers are voluntary, because the review compares every revision with the previous version and the next round's reports say what remains open.

We have addressed most of the reviewers’ comments. Specifically, the set.seed argument is what we argue against. We have added the Section Conflicts of Interests, and uploaded the the updated script with the R code.

required The nearest prior work is the authors' own earlier preprint "Taking R to its limits: 70+ tips" (Tsagris and Papadakis, 2018, PeerJ Preprints, doi:10.7287/peerj.preprints.26605v1), which the search found and which does not appear in the reference list. The current manuscript states "to the best of our knowledge, this is the first time such a long list has been compiled in one place," and the response letter itself refers to "an earlier version of this paper, which can be found on the web." That earlier version already compiled a comparable list, so the first-compilation claim is not accurate as written without citing and positioning against it. Please cite the 2018 preprint and state what the present version adds relative to it (the count moving from 70+ to 91, the numerical-stability section, the data.table and matrix additions), or qualify the first-compilation sentence.
Done
required Tip 17 option a3 still misaligns in the same family of cases the prior round flagged. The author removed `reorder = FALSE`, so `rowsum(x, ina)` now returns groups in sorted order and divides by `as.vector(tabulate(ina))`. This agrees only when the group codes are the consecutive positive integers 1..k. When the codes have a gap, say `ina = c(1,3,3,1)`, `rowsum` returns two rows while `tabulate(ina)` returns `c(2,0,2)` of length three, and the division recycles, so each group mean is divided by the wrong count. Option a2 with `table(ina)` is safe because `table` returns only present levels in sorted order. Either drop a3, or add the "consecutive strictly positive integers" caveat that Tip 16 already states for `tabulate` and cross-reference it.
Done
required The manuscript still carries no competing-interest statement. The authors maintain Rfast, Rfast2 and estats, and the paper recommends these packages as faster in tips 62 (hd.eigen), 70 (Rfast::Dist), 72 (colMedians) and across Sections 9 and 10. Three reviewers asked for this in the prior round, and the response letter defers it ("We will ask the editors what to write and where") rather than adding it. The disclosure is required regardless of how the recommendations are judged. Add a short statement naming Rfast, Rfast2 and estats as packages the authors maintain, placed before the references. A usable form: "M. Tsagris and M. Papadakis are the maintainers of the R packages Rfast, Rfast2 and estats, which are recommended in this paper. The authors declare no other competing interests."
Done
required Add the competing-interest statement. It is still absent from the manuscript, and the paper recommends Rfast, Rfast2, estats and hd.eigen. A one-line declaration suffices and I give wording below.
Done
required State the BLAS in use and add a reproducibility script for the reported timings. Several matrix comparisons (crossprod vs t(X) %*% Y, princomp vs prcomp, float throughput) depend on which BLAS is linked, and reference BLAS results can invert under OpenBLAS or MKL. Provide the benchmark script plus sessionInfo and the BLAS identity, or qualify these comparisons as reference-BLAS results. This was asked in the previous round and is still open.
Done
required Where an authored package is recommended as faster, compare it against the strongest alternative, not base R alone. Either benchmark Rfast/estats functions against matrixStats, collapse and data.table, or soften the superiority claims to "an alternative to base R". This was asked in the previous round and is still open.
Done
required Ship a runnable benchmark script that regenerates the two printed tables (tips 16 and 46) with a fixed seed, the R version, and the BLAS named, or remove the printed numbers. The uploaded file reproduces code chunks but does not run end to end. This was asked in the previous round and is still open.
Done
required Add data.table coverage beyond `fread`: keyed joins, grouped aggregation with `[, by = ]`, and update by reference, cross-referenced from tips 12 and 17. This was asked in the previous round and is still open.
Done
recommended The reproducible parallel RNG note (Section 9) is still absent. The decline rests on timing, but the point is reproducibility of simulation results.
Declined We argue against it because the goal is on the time comparisons, not the reproducibility of some random number that do not affect time.
recommended Add collapse (fmean, fsum, fvar) to the grouped-operation tips (17, 38). This was asked in the previous round and is still open.
Declined If we add them then we would have to add many more in other tips.
required State the BLAS in use and add a reproducibility script for the reported timings. Several matrix comparisons (crossprod vs t(X) %*% Y, princomp vs prcomp, float throughput) depend on which BLAS is linked, and reference BLAS results can invert under OpenBLAS or MKL. Provide the benchmark script plus sessionInfo and the BLAS identity, or qualify these comparisons as reference-BLAS results.
Done
required Add a competing-interest statement. The authors maintain Rfast, Rfast2 and estats, which the paper recommends as faster (tips 64, 72, Section 10).
Done
required Where an authored package is recommended as faster, compare it against the strongest alternative, not base R alone. Either benchmark Rfast/estats functions against matrixStats, collapse and data.table, or soften the superiority claims to "an alternative to base R".
Done
required Ship a runnable benchmark script that regenerates the two printed tables (tips 16 and 46) with a fixed seed, the R version, and the BLAS named, or remove the printed numbers. The uploaded file reproduces code chunks but does not run end to end.
Done
required Add data.table coverage beyond `fread`: keyed joins, grouped aggregation with `[, by = ]`, and update by reference, cross-referenced from tips 12 and 17.
Done
recommended Add collapse (fmean, fsum, fvar) to the grouped-operation tips (17, 38).
Declined If we add them then we would have to add many more in other tips.
Round 3Accepted3 reviewers
AcceptedSigned by Matthias Templ2026-11-14 · orcid 0000-0002-8638-5276

The editor's note

Final acceptance of version 1, after the editor read the preview of the article. The journal ran the code end to end on Linux. Every printed comparison keeps its direction, and most speed-up factors are smaller than on the authors’ laptop.

Decision letter2026-11-14Congratulations, your manuscript has been accepted for publication in JRepStat. Production begins now.

Congratulations, your manuscript has been accepted for publication in JRepStat. Production begins now.

Where it is not on file yet, we still need the following for production.

  • a valid ORCID iD for every author
  • a captured computational environment (dependencies/lockfile/container)
  • a signed determinism attestation for the entry-point command

Reviews

Report Reviewer 1recommends acceptThe one required point is settled. The new Conflicts of Interests section names Rfast, Rfast2 and estats as packages the authors maintain and declares no other competing interest, which is the statement I asked for.

Written by the journal's review engine in the role of the application reviewer, and read by the editor before the decision. How the engine works is on the peer review page.

The one required point is settled. The new Conflicts of Interests section names Rfast, Rfast2 and estats as packages the authors maintain and declares no other competing interest, which is the statement I asked for.

My two recommended points are both addressed in substance. The reader-facing BLAS caveat is now in two places: the introduction states the BLAS version and that speed-up factors may vary across machines and operating systems, and tip 50 carries the specific warning that the crossprod margins can narrow or reverse under an optimized multithreaded BLAS. Tip 15 adds a matching note about fixed JIT and BLAS settings, and tip 44 now has the princomp precision footnote. On the bare ratios, tip 14 gained a footnote attributing the factor to the Windows laptop, and the authors declined to annotate every remaining ratio (tips 52, 75, 86) on the grounds that they would then have to add the same note across many tips. That decline convinces me: the global caveat in the introduction now covers the reader who meets any single ratio, so repeating it at each tip would add length without adding information.

Nothing remains open, and the paper reads cleanly as it now stands.

Numbered suggestions to the authors:

(none)

Report Reviewer 2recommends acceptOf the three points I raised, all are met.

Written by the journal's review engine in the role of the methodology reviewer, and read by the editor before the decision. How the engine works is on the peer review page.

Of the three points I raised, all are met.

The competing-interest point is settled. A Conflicts of Interests section before the references states that both authors maintain Rfast, Rfast2 and estats and that these are recommended in the paper, which is the disclosure the venue expects.

The tip 17 alignment point is also settled. Variant a3 still divides rowsum(x, ina) by as.vector(tabulate(ina)), and the authors took the route of adding the condition rather than dropping a3. The new note tells the reader that tabulate returns frequencies only for consecutive strictly positive integers and should be treated with the caution of tip 16. That removes the silent-misalignment trap for a reader who copies the line.

The BLAS point, which I had kept recommended, is addressed more fully than I asked. The introduction now gives the BLAS version alongside LAPACK and states that speed-up factors may vary across machines and operating systems, and tips 15 and 50 add the backend caveat at the two places it matters most. A reader will now read the printed margins with the right expectations.

Nothing is open.

Numbered suggestions to the authors:

(none)

Report Reviewer 3recommends acceptThe single required point that remained open, the competing-interest disclosure, is now met. The new “Conflicts of Interests” section states that the authors maintain Rfast, Rfast2 and estats and that these are recommended in the paper, which is the disclosure the venue expects when an authored package is promoted as faster. That settles it, and nothing required remains.

Written by the journal's review engine in the role of the software reviewer, and read by the editor before the decision. How the engine works is on the peer review page.

The single required point that remained open, the competing-interest disclosure, is now met. The new “Conflicts of Interests” section states that the authors maintain Rfast, Rfast2 and estats and that these are recommended in the paper, which is the disclosure the venue expects when an authored package is promoted as faster. That settles it, and nothing required remains.

On the parallel RNG note, the authors again declined on the ground that the goal is timing and not the reproducibility of draws that do not affect timing. The reason does not fully engage the point I raised, which was about reproducing the results of a simulation study a reader parallelises using the Section 9 recipe, not about the timings. It is a legitimate reasoned decline and it was a recommendation, so it does not hold the paper. I leave it there.

On the BLAS, the intro now reports “BLAS version is 4.61.24651.0” alongside LAPACK 3.12.1, and the uploaded script carries the session info. That is a partial answer. A version string does not identify whether the benchmarks ran against the single-threaded reference BLAS that ships with Windows R, or an optimized multithreaded backend, and the tips on crossprod, princomp and float narrow or invert across those. Naming the implementation would let a reader place the ratios. This is a one-word addition and does not hold the paper.

Numbered suggestions to the authors:

  1. optional In the intro, name the BLAS implementation used for the benchmarks (for example the reference BLAS shipped with Windows R), since the version string alone does not tell the reader whether the matrix timings came from a single-threaded or an optimized multithreaded backend.

Peer review record (PDF) · How open review works

Abstract

R has many capabilities, most of which are unknown to many of its users and are waiting to be discovered. For this reason we provide a collection of more than 90 tips on how to write truly efficient code without having to program in C++, general programming advice, and tips for avoiding errors and numerical overflows.

1 Introduction

R is a scripting language and is not computationally efficient when compared to compiled languages, yet it has strong capabilities that are unknown to most of its users. Efficient code is very important in large–scale datasets, computations, or simulation studies. Efficient R programming has been treated before. (Wickham, 2015) devotes several chapters in his book to performance and memory, (Burns, 2011) catalogues common pitfalls in his book The R Inferno, and Gillespie & Lovelace (2016) gave a book–length treatment.

We have listed 91 tips that can help the user write more efficient code, use less memory, and become more familiar with R and its commands. The present list is oriented towards statistical computing, with an emphasis on matrix algebra, regression and simulation, includes many tips not documented elsewhere, and treats numerical stability alongside speed. The list is not exhaustive and we are certain there are tips we are not aware of. This paper is an updated extension of (Tsagris & Papadakis, 2018), where we removed some tips and added more than 20 tips. We ran some of the functions on a Dell laptop with Intel Core i7–1355U processor, 16GB RAM, 500 GB SSD and Windows OS, using R 4.6.1, and compared them to R’s built–in functions. We have not compared them to competing packages. In the uploaded R code we have added the session info of the R environment we used. The LAPACK version is 3.12.1, and BLAS version is 4.61.24651.0 (single threaded). We emphasize that the speed–up factors may vary across machines and or operating systems.

The speed–ups one obtains in small samples or low dimensions will be small, but in larger datasets the differences are observable. To put it simply, for someone who needs a simple car, a very expensive car or a jeep might not be of much use, especially if they do not go off–road. But for the user who needs a jeep, every bit of computational power, every second they can gain, matters. One might observe a time difference of only 5 seconds in the whole process. Differences from 40 seconds to 12 seconds, or to 22 seconds, are still worthwhile. Sometimes one tip saves 1 second, then another tip saves 1 more second, and so on, until 5 seconds are saved. For a researcher who has to run 1,0001,000 simulations, this amounts to 5,0005,000 seconds. Our motto is that every decrease in time or memory matters.

2 Measuring execution time

In order to measure the time a process, computation or simulation needs, we can do the following

runtime <- proc.time()
## put your function here
runtime <- proc.time() - runtime
## runtime gives you 3 numbers (all in seconds) like the ones below
user  system elapsed 
0.18    0.07    3.35 

The elapsed value is the desired metric. Alternatively, the package microbenchmark (Mersmann, 2015) allows for the comparison of two or more functions, measuring their execution time even at the nanosecond scale. The package bench (Hester & Vaughan, 2025) does the same and also reports the memory allocated.

3 General advice

We begin with a list of general programming advice.

  1. When writing code, leave spaces between operations and parentheses, and indent the lines inside for loops. Put a comment at the end of every loop so as to know to which loop each closing bracket refers. This is really helpful if the code is long. Make the code readable and clean, not only for someone else, but mainly for ourselves. Clean code is easier to understand and edit. A good programmer makes mistakes, but detects them fast. If the code is long and has no spaces and no comments, spotting mistakes can become a difficult task.

  2. Profile before optimizing. We are usually wrong about where our code spends its time. Rprof interrupts R every 20 milliseconds (by default) and records which function is running; summaryRprof then reports the time spent in each function. Only the functions at the top of the list are worth optimizing.

    Rprof("prof.out")
    ## put your function here
    Rprof(NULL)
    summaryRprof("prof.out")$by.self
    ## profvis::profvis( your function ) gives the same 
    ## information as an interactive graph

    The function below is a worked example of profiling. It appends to a vector inside a loop, sorts it and returns the mean.

    f <- function(n) {
      x <- NULL
      for ( i in 1:n )  x <- c(x, sqrt(i))
      y <- sort(x)
      sum(y) / length(y)
    }
    Rprof("prof.out", interval = 0.01)
    a <- f(1e5)
    Rprof(NULL)
    summaryRprof("prof.out")$by.self
                 self.time self.pct total.time total.pct
    "c"               5.31    99.81       5.31     99.81
    "Sys.getenv"      0.01     0.19       0.01      0.19

    Almost all the time is spent in c(), which copies the whole vector at every iteration. The sorting, which one might have suspected, is negligible. Preallocating removes the bottleneck.

    x <- NULL
    for ( i in 1:n )  x <- c(x, sqrt(i))  ## not efficient
    x <- numeric(n)
    for ( i in 1:n )  x[i] <- sqrt(i)     ## efficient
    x <- sqrt(1:n)                        ## even better
  3. Verify before trusting a speed–up. Every time a slow implementation is replaced by a faster one, compare them on the same input. Use all.equal, which allows for a small tolerance, and not identical or ==, because the order of the floating–point operations may have changed (see also the section on numerical overflows). Results that are equal in theory differ in the last bits when the operations are performed in a different order, which is exactly the situation when we compare a fast and a slow version of a function. Convergence checks in iterative algorithms suffer from the same problem and may never terminate.

    0.1 + 0.2 == 0.3                            ## FALSE
    isTRUE( all.equal(0.1 + 0.2, 0.3) )         ## TRUE
    while ( u.new != u.old )                    ## may never stop
    while ( sum( abs(u.new - u.old) ) > tol )   ## correct
    all.equal(fast(x), slow(x))                 ## TRUE, or a message 
  4. Avoid unnecessary calculations. In a discriminant analysis setting, for example, there is no need to calculate constant terms, such as log⁡(2π)\log{(2 \pi)}, for each group and at every iteration. This only adds time, takes memory, and does not affect the algorithm or the result. The same holds for the Euclidean or the Hellinger distance: the square root and the multiplication by a common factor make no difference to the ordering of the distances and, if they can be avoided, they should be.

  5. Try to make the mathematics, and hence the operations, as simple as possible. The partial correlation coefficient can be computed in many ways, two of which are via two regression models or via the simple correlation matrix. The second is much faster.

  6. Suppose we have a function that uses many regression models, not necessarily from different downloadable R packages, but even from R’s built–in models. We should not create a separate function for each model. This seems like the obvious thing to do, simply because different regression models have different signatures and the hypothesis test for each of them is different: lm uses an FF test, glm uses an FF or a χ2\chi^2 test, and so on.

    The optimal solution is to write one function that includes all regression models and their arguments. This way we have one inclusive function for all models instead of many. Every time we want to add a new regression model we add it to this function and do not have to create a new one. This results in fewer files and less memory.

  7. It is important to understand how R works, what operations do, and what we can and cannot do. The command mahalanobis, for example, uses the following line to calculate the distances.

    rowSums(x %*% cov * x)

    The first key message is that the function performs one, and not two (as one would expect), matrix multiplications. Secondly, the user is given the chance to see that they can apply these types of operations. Thirdly, they are given the chance to make this function faster.

  8. If we have a vector x of integer numbers, it is preferable to store it as as.integer(x) rather than as.numeric(x). The former requires 4 bytes per element, the latter 8.

  9. Copy–on–modify. When two names refer to the same object and one of them is modified, R silently copies the object first. Modifying a large object inside a function therefore duplicates it. The function tracemem prints a message every time an object is copied and is the simplest way to find unexpected copies.

    x <- rnorm(1e7)
    tracemem(x)
    y <- x        ## no copy yet, x and y share the same memory
    y[1] <- 0     ## now y is copied
    x[1] <- 0     ## no copy, x has a single reference
  10. The byte–code compiler. The compiler package translates R functions into byte–code, which runs faster, especially for loops and scalar arithmetic. Since R 3.4.0 the just–in–time compiler is enabled by default at its highest level, so every function is compiled the first time it is called and the user does not have to do anything. It can be checked and used explicitly as follows.

    compiler::enableJIT(-1)   ## returns the current level, 3 = everything
    f <- compiler::cmpfun(f)  ## compile a function explicitly

    Note that the compiler cannot vectorize a loop for us; the tips that follow remain necessary.

4 Simple functions

We continue with a list of simple functions that will help us make our code more efficient and faster.

  1. Not all packages, or R itself, have the fastest implementations. The function mean is slower than sum(x)/length(x), because mean is a generic function (method dispatch takes place) and performs two passes over the data in extended precision in order to reduce the rounding error, whereas sum is a .Primitive function, implemented directly in C, that performs a single pass. If we type sum we will see it is a .Primitive function, whereas crossprod, for example, is an .Internal function. Another example of a more advanced function is to perform many univariate logistic regressions and each time calculate the deviance of the model. If we create our own efficient functions, we may be surprised to see that they are faster than R’s built–in functions1.

  2. The commands cor and cov are two very fast functions that can be used to calculate the correlations or covariances between a vector and a matrix very efficiently. Many simple regression models can be computed using these two commands.

  3. Search for functions that take less time. For example, lm(y ∼\sim x) calls lm.fit(x, y) after building the design matrix from the formula. If we only require the coefficients, we should use lm.fit directly. The syntax is a bit different, since x must be the design matrix, but the speed is also very different, especially in large cases. The command .lm.fit(x, y) is even faster.

  4. It’s your algorithm. Tsagris (2017) showed that conditional G2G^2 tests of independence can become roughly 3–4 times faster if they are run using Poisson log–linear models instead of constructing the appropriate tables using for loops2. (Chatzipantsiou et al., 2019) proposed an extremely fast algorithm for obtaining permutation–based and bootstrap–based p–values in the correlation and the two sample tt–test cases, respectively. There are many ways to perform a computation; we should choose or implement the most appropriate and most efficient one. For example, in order to generate vectors from the multivariate normal distribution we may use the spectral or the Cholesky decomposition. The latter is faster. In general, we should try to find the optimal mathematical method for our problem.

  5. Suppose we want to center some data. We can try with apply

    cent <- function(x) x - mean(x)
    a1 <- apply(x, 2, cent)

    or use one of the following alternatives

    a2 <- scale(x, center = TRUE, scale = FALSE) 
    m <- colMeans(x)
    a3 <- sweep(x, 2L, m)
    a4 <- t( t(x) - m ) ## see the section on matrices
    dm <- dim(x)
    n <- dm[1]
    p <- dm[2]
    a5 <- x - rep( m, rep(n, p) ) 

    We generated a matrix with 10,000 rows and 20 columns. The time results using the package microbenchmark are as follows

    Unit: microseconds
    expr    min       lq      mean   median       uq     max neval
    a1   1317.6  1494.80  2338.510  2215.30  2974.20  3878.8    20
    a2    686.5   774.05  1019.975   890.95  1076.40  2968.4    20
    a3    662.0   785.30  1146.100   897.40  1274.05  2912.3    20
    a4    641.6   668.70   929.645   696.75   875.85  2539.2    20
    a5    298.0   325.55   507.210   339.95   454.60  2610.5    20

    Note that when measuring time with this or any similar package, a single laptop with fixed JIT and BLAS settings limits how far the ratios carry.

  6. A very useful command is tabulate.

    table(iris[, 5])
    tabulate(iris[, 5])

    Two differences between them are that table returns the values as names, whereas tabulate returns only the frequencies. tabulate works with factor variables as well. But if we have a numerical vector, we should make sure the numbers are consecutive and strictly positive, i.e. no zero is included.

    x <- rep(0:5, each = 4)
    table(x)
    tabulate(x)  ## 0 is missing
    x <- rep(c(1, 3, 4), each = 5)
    table(x)
    tabulate(x)  ## there is a 0 appearing indicating the absence of 2

    The command tabulate is many times faster than table. For discriminant analysis algorithms tabulate is more useful, both because of speed and because it returns a 0 for a value with zero frequency. The drawback arises when we have negative numbers, zeros, or positive numbers that are not consecutive. If we want speed, we should formulate our data to match the requirements of tabulate.

  7. To extract the mean vector of each group we can use a for loop or

    a1 <- aggregate(x, by = list(ina), mean)

    where ina is a numerical variable indicating the group. A faster alternative is the built–in command rowsum

    a2 <- rowsum(x, ina) / as.vector( table(ina) )
    ## a bit faster option is a3 below
    a3 <- rowsum(x, ina) / as.vector( tabulate(ina) )  

    Note that this command works also for matrices. Note though that tabulate returns the frequency of consecutive strictly positive integers and should be treated with caution as the previous tip mentions. An alternative would be to use the package data.table (Barrett et al., 2026)

    library(data.table)
    dt <- as.data.table(x)                  ## x is the numeric matrix
    dt[, ina := ina]                        ## add the grouping variable
    a1 <- dt[, lapply(.SD, sum),  by = ina] ## group sums
    a2 <- dt[, lapply(.SD, mean), by = ina] ## group means
  8. It is suggested to use which.min(x) and which.max(x) instead of which( x == min(x) ) and which( x == max(x) ) to find the position of the minimum and maximum, respectively. The former perform a single pass over the data, the latter two.

  9. Incremental calculations. An example is the first–order partial correlations, which can be computed from the simple correlations with fewer calculations. In general, if our function can perform calculations incrementally, the boost in speed can be very high.

  10. When calculating operations such as sum(a * x), where x is a vector or a matrix and a is a scalar, write a * sum(x). The two are equal by the distributive law of multiplication over addition, ∑i=1naxi=a∑i=1nxi\sum_{i=1}^n a x_i = a \sum_{i=1}^n x_i, so we are free to change the order of the operations. In the first case, the scalar is multiplied with all elements of the vector (many multiplications), whereas in the second case the sum is calculated first and then a single multiplication between two numbers takes place.

    sum(a * x)  ## n multiplications and n-1 additions
    a * sum(x)  ## n-1 additions and 1 multiplication
  11. Suppose we want to calculate the factorial of some integers and most (or all) of those integers appear more than once (Poisson, beta binomial, beta geometric, or negative binomial distribution, for example). Instead of performing the operation for each element, we can do it for the unique values only and weight each result by its frequency, as in the example below. Note, however, that this trick does not always pay off. It will work in the case where we have many repeated integers and a for or a while loop, and hence we have to calculate the factorials repeatedly.

    x <- rpois(10000, 5)
    sum( lgamma(x + 1) )
    y <- sort( unique(x) )
    ny <- as.vector( table(x) )
    sum( lgamma(y + 1) * ny )
  12. If we use the glm or lm commands multiple times, then we should write

    glm(y ~ x, family = ..., y = FALSE, model = FALSE)
    lm(y ~ x, y = FALSE, model = FALSE)

    The two extra arguments y = FALSE, model = FALSE reduce the memory requirements of the fitted object.

  13. When calculating log⁡(1+x)\log{\left(1+x\right)} use log1p(x) instead of log(1 + x). The advantage is accuracy: when xx is very small, 1+x1 + x is rounded to 1 and log(1 + x) returns 0, whereas log1p(x) returns the correct value. The same holds for ex−1e^x - 1 and expm1(x).

    x <- 1e-17
    log(1 + x)   ## 0
    log1p(x)     ## 1e-17
  14. Vectorization can save a tremendous amount of time even in small datasets. Try to avoid for loops by using vectorized operations or matrix multiplications. For example, instead of

    for (i in 1:n) y[i] <- x[i]^2

    we can write

    y <- x^2

    This is a very easy example, but the point is made. Vectorization requires a lot of thinking and is not always applicable, but when it is, it can yield substantial computational savings.

  15. A useful command is outer. An example is where we have two vectors x and y and we want to add each element of y to each element of x. The result is a matrix.

    z <- matrix(0, nrow = length(x), ncol = length(y) )
    for ( i in 1:dim(z)[1] )  z[i, ] <- x[i] + y
    ## The above task can take place a lot faster by typing 
    outer(x, y, "+")
  16. The command sort has an extra feature: by specifying index.return = TRUE, the outcome is a list with the sorted numbers along with their ordering indices. That is, sort(x, index.return = TRUE) sorts the numbers and returns their order as if we had used order separately.

  17. We can partially sort a vector. In the kk–NNNN algorithm, for example, we want the kk smallest distances. There is no need to sort all the distances, only the kk smallest: sort(x, partial = 1:k).

  18. Many functions call internal functions. sort, for example, calls sort.int, and sample calls sample.int. Calling the internal function directly avoids the argument checking of the wrapper.

  19. Suppose we are given many matrices in a list, A, and wish to stack them one under the other into a new matrix. The command to do this efficiently is

    do.call(rbind, A)
  20. Use seq_len(n) instead of 1:n and seq_along(x) instead of 1:length(x) in loops. When n is 0, 1:n is c(1, 0) and the loop runs twice on non–existent elements, whereas seq_len(0) is empty and the loop is skipped.

    for ( i in 1:length(x) )    ## fails when x is empty
    for ( i in seq_along(x) )   ## correct
  21. Use vapply instead of sapply when the function returns a value of known type and length. sapply inspects all the results in order to decide what to return, whereas vapply is told in advance, allocates the result once, and fails if a result has the wrong type.

    sapply(x, f)               ## classical
    vapply(x, f, numeric(1))   ## more efficient and safer
  22. Use anyNA(x) instead of any(is.na(x)). The latter allocates a logical vector of the same length as x and scans it entirely, whereas the former stops at the first missing value.

    any( is.na(x) )  ## classical
    anyNA(x)         ## more efficient
  23. When flattening a list with unlist, drop the names if they are not needed. Constructing the names is often more expensive than the flattening itself.

    unlist(x)                     ## classical
    unlist(x, use.names = FALSE)  ## more efficient
  24. The vectorized ifelse evaluates both branches in full and carries a large overhead. For a scalar condition use if-else, and for numeric vectors use arithmetic on the logical condition.

    ifelse(test, 1, 2)             ## slow for a scalar test
    if (test) 1 else 2             ## efficient
    ifelse(x > 0, x, 0)            ## classical
    x * (x > 0)                    ## more efficient

    Note however, that these two differ when x contains NA, so users should not swap them blindly.

  25. For binning a numerical vector into intervals use findInterval instead of cut. cut constructs a factor with character labels, whereas findInterval returns the integer index of the interval directly, which is what is usually needed afterwards (for tabulate or rowsum).

    as.integer( cut(x, breaks) )   ## classical
    findInterval(x, breaks)        ## more efficient

5 Calculations involving matrices

R is not designed to handle large–scale datasets, yet there are many ways to handle matrices efficiently, and we present some tricks below.

  1. Use colMeans, rowMeans, colSums and rowSums instead of apply(x, 2, mean), apply(x, 1, mean), etc., as they are extremely fast. In addition, many really fast functions can be built using these commands. In general, we should avoid apply and aggregate whenever possible. For the median, though, there is no built–in alternative, and apply(x, 2, median) should be used instead of a for loop going through every column of the matrix. The for loop is not slower, but the apply is neater.

  2. In the same spirit as .lm.fit, the functions .colSums, .rowSums, .colMeans and .rowMeans are the internal versions of colSums etc. They skip the argument checks, at the price of passing the dimensions explicitly. The gain is noticeable when they are called many times on small matrices.

    colSums(x)               ## classical
    .colSums(x, n, p)        ## more efficient inside loops
  3. If we have to use a for loop going through the rows of a matrix, consider transposing the matrix and then going through its columns.

  4. If we are given a matrix and, inside a for loop, we would like to extract some specific columns/rows each time, we can instead store the indices of the columns/rows inside the for loop and, outside the loop, extract the columns/rows once and perform the operations we want.

  5. If we want the number of rows or columns of a matrix X, we should not use nrow(X) or ncol(X), but dim(X)[1] or dim(X)[2], as they are roughly 2 times faster. nrow and ncol are R–level functions that call dim and index the result, so we pay for an extra function call. Note though that the benefit is very tiny, since both functions require nanoseconds, and the time gain seem might seem negligible. We mention this tip here though to help the reader develop the efficient programming way of thinking.

  6. Suppose we have a matrix X and we want the position of the maximum for each row. The obvious solution is apply(X, 1, which.max). The efficient solution is max.col(X). Note that by default max.col breaks ties at random; use max.col(X, ties.method = "first") to obtain the same result as which.max.

  7. If we want to subtract a vector from a matrix in a row–wise fashion, we should be aware of the fact that R does it column–wise. This is because R reads, writes and stores data in a column–wise fashion. For example, let X be a matrix and y a vector whose length is equal to the number of columns of X. We should type

    t(X) - y
  8. If we transpose a matrix and never use the initial matrix in the subsequent steps, it is best to delete the initial matrix, or even better, to store its transpose in the same object. That is, if we have a matrix X, we should type

    Y <- t(X)  ## not suggested
    X <- t(X)  ## suggested

    We repeat that this applies only when X is not used again in later steps. The reason is memory saving: if X is big and we keep a second object as big as the first one, we request extra memory for no reason.

  9. Use the command princomp instead of prcomp for principal component analysis3. We generated a matrix with 10,000 rows and 50 columns to benchmark this and the results are presented below.

    Unit: milliseconds
    expr             min       lq      mean   median        uq      max  neval
    prcomp(x)    43.0756  45.2539  46.48306  46.2098  47.53110  50.5531     20
    princomp(x)  24.5183  26.3287  29.78383  28.4339  30.25745  51.3666     20
  10. Create vectors or matrices of the required size from the start. Instead of making a vector longer each time using c(), create an empty vector with the required size. The commands rbind and cbind are useful, but come at a heavy price: each call allocates a new object and copies all the data, so they are very expensive when called many times (see the profiling example in the general advice).

    x <- numeric(n)          ## vector of n zeros
    x <- integer(n)          ## integer vector
    x <- matrix(0, n, p)     ## n x p matrix
    x <- vector("list", n)   ## list of n NULLs
  11. For group covariance matrices the command by could be used. The matrices are stored in a list and the command simplify2array is then needed to convert the list to an array, in order to calculate, for example, the determinant of each matrix. A for loop is faster.

  12. What if we have an array of matrices and want to calculate the sum or the mean of all the matrices? The obvious answer is apply(x, 1:2, mean). Since R works column–wise, we can instead use t( colSums( aperm(x) ) ) and t( colMeans( aperm(x) ) ) for the sum and the mean, respectively.

    x <- array( dim = c(1000, 10, 10) )
    for (i in 1:10) x[, , i] <- matrix( rnorm(1000 * 10), ncol = 10 )
    a1 <- apply(x, 1:2, mean)
    a2 <- t( colMeans( aperm(x) ) ) 
  13. If we want to calculate the logarithm of the determinant of a matrix X, instead of log( det(X) ) we can type determinant(X, logarithm = TRUE), as it is slightly faster for small matrices. For big matrices, say of dimensions 100×100100 \times 100 or more, the difference becomes negligible.

  14. Suppose we want the Euclidean distances of a single vector from many others (say thousands). The inefficient way is to calculate the distance matrix of all points and take the row that corresponds to our vector. An efficient way is to use the Mahalanobis distance with the identity matrix as the covariance matrix.

    x <- rnorm(50)
    y <- matrix( rnorm(1000 * 50), ncol = 50 )
    a1 <- dist( rbind(x, y) )  ## inefficient way
    Ip <- diag(50)
                               ## below is a better way
    a2 <- sqrt( mahalanobis( y, center = x, cov = Ip, inverted = TRUE ) )

    Another way is the following

    z <- t(y) - x              ## R recycles column--wise
    a3 <- sqrt( colSums(z^2) )
  15. Calculating 𝐗⊤𝐘{\textbf{X}}^\top{\textbf{Y}} as t(X) %*% Y instead of crossprod(X, Y) forces R to allocate a transposed copy of X before the multiplication, whereas crossprod passes the transposition flag to the underlying BLAS routine and no copy is made. Note however, that these margins depend on the linear algebra backend and can narrow or reverse under an optimized multithreaded BLAS.

  16. Similarly, the product 𝐗⊤𝐗{\textbf{X}}^\top{\textbf{X}} of an n×pn \times p matrix is computed faster by crossprod(X) than by the explicit matrix multiplication, since the result is known to be symmetric.

    t(X) %*% Y       ## classical
    crossprod(X, Y)  ## more efficient
    X %*% t(Y)       ## classical
    tcrossprod(X, Y) ## more efficient
    t(X) %*% X       ## classical
    crossprod(X)     ## more efficient
  17. Let 𝑿\mathbf{X} and 𝒎\mathbf{m} be a matrix and a vector, and suppose we want the sum of their elementwise product. There are two ways to do it.

    sum(m * t(x))  
    sum(x %*% m)  ## more than 2 times faster
  18. When working with arrays it is more efficient to have them transposed. For example, if we have KK covariance matrices of dimension p×pp \times p, we would naturally create an array of dimensions c(p, p, K). Make its dimensions c(K, p, p) instead. If we want, for example, to divide each matrix by a different scalar, in the first case we have to use a for loop, whereas in the transposed case we simply divide the array by the vector of scalars.

  19. If we want to invert a positive definite matrix (e.g. a covariance matrix) we should use chol2inv( chol( X ) ), as it is faster than solve(X).

  20. To invert a matrix (not necessarily positive definite) and multiply the result with a vector or another matrix, there are two ways

    solve(X) %*% Y  ## classical
    ## a much more efficient way is to not invert the matrix X
    solve(X, Y)   
  21. The quantity tr(𝐗⊤𝐗)\text{tr}\left({\textbf{X}}^\top{\textbf{X}}\right) can be evaluated either via

    sum( diag( crossprod(X) ) )  

    or, faster, via

    sum(X * X) ## or 
    sum(X^2)   

    Note that for a square matrix tr(𝐗2)\text{tr}\left({\textbf{X}}^2\right) is a different quantity, equal to sum(X * t(X)).

  22. Similarly, the trace tr(𝐗⊤𝐘)\text{tr}\left({\textbf{X}}^\top{\textbf{Y}}\right) can be computed either via

    sum( diag( crossprod(X, Y) ) )  ## just like before

    or, faster, via

    sum(X * Y)  ## faster, like before
  23. In the same spirit, if we want the diagonal of the product of two matrices, type

    diag( tcrossprod(X, Y) )  ## for example
    rowSums(X * Y)            ## this is faster
  24. Suppose we have two matrices 𝑨\mathbf{A}, 𝑩\mathbf{B} and a vector 𝒙\mathbf{x} and we want 𝑨𝑩𝒙\mathbf{ABx} (the dimensions must match, of course).

    A %*% B %*% x    ## inefficient way
    A %*% (B %*% x)  ## efficient way

    In the first case we perform a matrix–by–matrix multiplication followed by a matrix–by–vector multiplication. In the second case we perform two matrix–by–vector multiplications, which require far fewer operations, and avoid extra calculations.

  25. For the reconstruction of a matrix from its eigendecomposition, there are two ways to do the multiplication

    s <- matrix( rnorm(100 * 100), ncol = 100 )
    s <- crossprod(s)
    eig <- eigen(s)
    vec <- eig$vectors
    lam <- eig$values
    a1 <- vec %*% diag(lam) %*% t(vec) 
    a2 <- vec %*% ( t(vec) * lam )  ## faster way
  26. The exponential term of the multivariate normal density can be calculated either using matrices or simply with the command mahalanobis. If we have many observations, many dimensions, or many groups, this can save a lot of time.

    x <- matrix( rnorm(1000 * 20), ncol = 20 )
    m <- colMeans(x)
    dm <- dim(x)
    n <- dm[1]
    p <- dm[2]
    s <- cov(x) 
    a1 <- diag( (x - rep(m, rep(n, p)) ) %*% solve(s) 
                %*% t(x - rep(m, rep(n, p)) ) ) 
    a2 <- diag( t( t(x) - m ) %*% solve(s) %*% ( t(x) - m ) ) 
    a3 <- mahalanobis(x, m, s)  ## much faster
  27. Suppose we want to compute the trace of the square of the correlation matrix 𝐑{\textbf{R}}. It is well known from linear algebra (Strang, 2023) that for a symmetric matrix 𝑨\mathbf{A}, its eigendecomposition is given by 𝐀=𝚪𝚲𝚪⊤{\textbf{A}}=\bm{\Gamma}\bm{\Lambda}\bm{\Gamma}^\top, where 𝚪\bm{\Gamma} is the matrix of eigenvectors and 𝚲\bm{\Lambda} is a diagonal matrix that contains the pp eigenvalues λ1,…,λp\lambda_1,\ldots,\lambda_p. Note that tr(𝐀)=∑j=1pλj\text{tr}({\textbf{A}})=\sum_{j=1}^p\lambda_j and tr(𝐀2)=∑j=1pλj2\text{tr}({\textbf{A}}^2)=\sum_{j=1}^p\lambda_j^2. This trick allows us to avoid computing the correlation matrix, multiplying it by itself and then summing its diagonal elements.

    R’s built–in function prcomp() computes principal components by singular value decomposition of the (centered) data matrix in a fast and memory–efficient manner. Its drawback is that it computes pp eigenvectors and pp eigenvalues, when in fact at most n−1n-1 eigenvalues are non–zero, since the rank of the correlation matrix is at most n−1n-1 when n<pn<p. Hence, instead of prcomp(), the function hd.eigen() available in Rfast can be applied. This function is optimized for the case n<pn<p and returns the first nn eigenvectors and eigenvalues. Thus, hd.eigen() is not only faster than prcomp() in high–dimensional settings, but also requires less memory. The function takes the original data (𝐘{\textbf{Y}}), standardizes them (𝐙{\textbf{Z}}), and performs the eigendecomposition of the matrix 𝐙𝐙⊤{\textbf{ZZ}}^\top. The sum of the squared eigenvalues divided by (n−1)2(n-1)^2 equals tr(𝐑2)\text{tr}({\textbf{R}}^2).

  28. Prefer matrices to data frames for numerical work. A data frame is a list of columns, so every operation on it goes through method dispatch, and extracting a row constructs a new data frame. If all the columns are numeric, convert once at the start of the function.

    for (i in 1:n)  f( df[i, ] )    ## very slow
    x <- as.matrix(df)
    for (i in 1:n)  f( x[i, ] )     ## much faster
  29. Use drop = FALSE when subsetting matrices. By default X[, 1] returns a vector, so a function that extracts X[, ind] will silently receive a vector when ind has length 1, and dim or colSums will fail. This tip is about correctness rather than speed.

    X[, ind]                ## vector when length(ind) == 1
    X[, ind, drop = FALSE]  ## always a matrix
  30. If a linear system involves a triangular matrix, e.g. the Cholesky factor of a covariance matrix, do not use solve, which treats the matrix as a general one. backsolve and forwardsolve exploit the triangular structure and solve the system in O(p2)O(p^2) instead of O(p3)O(p^3) operations.

    L <- chol(S)                ## upper triangular, S = t(L) %*% L
    solve(L, b)                 ## classical
    backsolve(L, b)             ## more efficient
    forwardsolve( t(L), b )     ## for the lower triangular factor
  31. When the matrix is symmetric, declare it. By default eigen checks for symmetry by comparing all pairs of elements; declaring it skips the check, uses the faster symmetric routine, and guards against a false negative due to rounding errors in a computed covariance matrix. If only the eigenvalues are needed, say so as well.

    eigen(S)                                       ## classical
    eigen(S, symmetric = TRUE)                     ## more efficient
    eigen(S, symmetric = TRUE, only.values = TRUE) ## eigenvalues only
  32. Sparse matrices. If most elements of a matrix are zero (contingency tables with many categories, adjacency matrices, design matrices with many dummy variables), the package Matrix (Bates et al., 2026) stores only the non–zero elements, and the cost of multiplication and solve scales with the number of non–zeros. Sparsity is lost by operations that fill in the zeros, e.g. adding a scalar or centering.

    library(Matrix)
    xs <- Matrix(x, sparse = TRUE)
    crossprod(xs)                    ## works as for a dense matrix
    solve(xs, b)
  33. Single precision. R stores real numbers in double precision (8 bytes). The package float (Schmidt, 2025) provides 32–bit (4–byte) matrices with the usual arithmetic and linear algebra defined on them. This halves the memory and roughly doubles the throughput of BLAS operations, at the cost of about 7 significant digits instead of 16. It is inappropriate for iterative algorithms where rounding errors accumulate.

    library(float)
    xf <- fl(x)               ## half the memory of x
    crossprod(xf)
    dbl( crossprod(xf) )      ## back to double precision
  34. Multiple responses in one call. If we need the regression of many response variables on the same design matrix (genome–wide analyses, permutation tests), we should not loop over the responses. lm.fit and .lm.fit accept a matrix of responses and fit all the regressions with a single QR decomposition of x. If the responses arrive one at a time, compute the QR decomposition once and reuse it.

    for (j in 1:q)  b[, j] <- lm.fit(x, Y[, j])$coefficients  ## classical
    b <- lm.fit(x, Y)$coefficients                            ## efficient
    q <- qr(x)           ## decompose once
    qr.coef(q, y1)       ## reuse for each response
    qr.coef(q, y2)
  35. Keep distances as a dist object. The function dist returns the lower triangle of the distance matrix as a vector of n(n−1)/2n(n-1)/2 elements. Converting it to a full matrix more than doubles the memory, and many functions (hclust, cmdscale) accept the dist object directly. If the full matrix is required, Rfast computes it directly in C++.

    d <- as.matrix( dist(x) )           ## classical, n x n matrix
    d <- dist(x)                        ## n(n-1)/2 vector, half the memory
    d <- Rfast::Dist(x)                 ## full matrix, much faster
    d <- Rfast::Dist(x, result = "vector")  ## lower triangle only
    d <- Rfast::dista(x, y)             ## distances between rows of x and y
  36. To sum many matrices of the same dimensions stored in a list A, use Reduce. This applies the operator cumulatively and allocates one result, instead of copying all the matrices into an array first.

    apply( simplify2array(A), 1:2, sum )  ## classical
    Reduce("+", A)                        ## more efficient
  37. The function quantile is surprisingly slow, because it sorts the whole vector and handles nine quantile definitions. If a single quantile is needed, use partial sorting. The kk–th smallest value is sort(x, partial = k)[k], and the default (type 7) quantile of order α\alpha interpolates between two order statistics.

    quantile(x, alpha)                        ## classical
    h <- (n - 1) * alpha + 1
    k <- floor(h)
    y <- sort(x, partial = c(k, k + 1))
    q <- y[k] + (h - k) * (y[k + 1] - y[k])   ## more efficient

    For the median, median already uses this trick, and colMedians of Rfast applies it column–wise.

6 Numerical optimization

  1. The command nlm is usually faster than optim for optimization purposes, but optim is more reliable and robust. In some cases optim with the argument method = "BFGS" can be faster, but these depend upon the function being minimized.

  2. If we have a function for which some parameters have to be positive, we should not use constrained optimization, but instead exponentiate the parameter inside the function. The parameter can take any value on the real line ℝ\mathbb{R}, but inside the function its exponentiated form is used. In the end, we simply take the exponential of the returned value. For its variance we use the δ\delta–method (Casella & Berger, 2002). The trick is to use a link function, similarly to generalised linear models.

  3. There are two ways to estimate the parameters of a distribution, the Dirichlet for example: either with the use of nlm, or via the Newton–Raphson algorithm. We performed some simulations and saw that Newton–Raphson can be at least 10 times faster. The same is true for the circular regression of Presnell et al. (1998) when comparing nlm with the E–M algorithm described by the same authors. Switching to E–M or Newton–Raphson, and not relying on nlm, can save a lot of time. If we have the description of the E–M or the Newton–Raphson algorithm available, we should implement it. Of the two, Newton–Raphson is faster.

  4. If we have an iterative algorithm, such as Newton–Raphson, E–M or fixed–point iteration, and we stop when the vector of parameters does not change any further, we should not use rbind, cbind or c() to store the whole sequence. Instead, we store only two values, vec.old and vec.new. That is, we should not type

    u[i, ] <- u[i - 1, ] + W %*% B  ## not efficient

    but

    u.new <- u.old + W %*% B        ## efficient

    So, at every iteration we keep two vectors only, not the whole sequence. The same is true for the log–likelihood or the criterion of interest. Unless we want to keep track of how the values change, our advice is to keep only the current and the previous value. Apart from being faster, this also uses less memory.

7 Numerical overflows

Numerical instabilities occur frequently when using real, not simulated, data. We mention these tricks because one should not sacrifice numerical stability for the sake of speed. When trying to speed up our code we experienced numerical instabilities and overflows, and we would like to share some of the issues we faced.

  1. The fitted values of a logistic regression model make use of the inverse logit function ex1+ex\frac{e^x}{1+e^x}. If xx is a very large number, both the numerator and the denominator overflow to Inf and the result is NaN. If, however, we write the formula in its equivalent form 11+e−x\frac{1}{1+e^{-x}}, the result is 1, as it should be.

    x <- 1000
    exp(x) / (1 + exp(x))   ## NaN
    1 / (1 + exp(-x))       ## 1
  2. The same is true for the Poisson regression, or other regressions that use the log link function. In those cases exe^x is used. It might be useful to consider using e−xe^{-x} if there is a possibility of having very large values, or simply standardize the predictor variables.

  3. Kernel functions are of the form ef(𝐗)he^{\frac{f({\textbf{X}})}{h}}, where hh is a scalar and 𝑿\mathbf{X} is a matrix. In order to speed up the calculations one could pre–compute ef(𝐗)e^{f({\textbf{X}})} and then raise the result to the power 1/h1/h for the different values of hh. This can easily result in overflow and Inf values and hence caution must be taken.

  4. The function log⁡(1+ex)\log{(1+e^x)} behaves like xx for large xx; in double precision the two become equal for x≳37x \gtrsim 37, and exe^x overflows for x>709x > 709, so that even log1p(exp(x)) returns Inf. The stable way to compute it is max⁡(x,0)+log⁡(1+e−|x|)\max(x, 0) + \log{\left(1 + e^{-|x|}\right)}.

    log1p( exp(x) )                     ## Inf for x > 709
    pmax(x, 0) + log1p( exp(-abs(x)) )  ## never overflows
  5. The product ∏i=1nxi\prod_{i=1}^nx_i, where 0<xi≤10 < x_i \leq 1, underflows to 00 very fast. In order to avoid this, we should compute e∑i=1nlog⁡xie^{\sum_{i=1}^n\log{x_i}}, or better, work with the logarithm of the product throughout.

    prod(x)             ## 0
    exp( sum(log(x)) )  ## correct
  6. We use the logarithm of the p–values and not the p–values themselves. This is very beneficial when our algorithm calculates and compares p–values. p–values underflow to zero when they are near 1e−3081e-308 (and subnormals to 5e−3245e-324), so R cannot sort them correctly since they are all considered equal. The logarithms of the p–values can be sorted correctly.

    pchisq(stat, dof, lower.tail = FALSE)                ## can be 0
    pchisq(stat, dof, lower.tail = FALSE, log.p = TRUE)  ## sortable
  7. The log–sum–exp trick. Quantities of the form log⁡∑i=1nexi\log{\sum_{i=1}^n e^{x_i}} appear in normalizing constants, mixture likelihoods, the softmax function and the E–step of the E–M algorithm. Computing them literally overflows when some xi>709x_i > 709 and underflows to −∞-\infty when all xi<−745x_i < -745. The stable formula is m+log⁡∑i=1nexi−mm + \log{\sum_{i=1}^n e^{x_i - m}} with m=max⁡ixim = \max_i x_i, since then the largest exponent is e0=1e^0 = 1.

    log( sum( exp(x) ) )          ## overflows
    m <- max(x)
    m + log( sum( exp(x - m) ) )  ## stable
    matrixStats::logSumExp(x)     ## the same, and row/column versions
  8. Work with log–densities. All the density functions of R accept log = TRUE and compute the logarithm directly, whereas log(dnorm(...)) underflows to −∞-\infty in the tails. Similarly, lgamma, lbeta, lchoose and lfactorial should be used instead of the logarithm of gamma, beta, choose and factorial, which overflow. Exponentiate, if at all, only at the very end.

    log( dnorm(x, m, s) )        ## -Inf for x far in the tail
    dnorm(x, m, s, log = TRUE)   ## correct
    log( choose(1100, 550) )     ## Inf
    lchoose(1100, 550)           ## correct
  9. Integer overflow. Integers in R are 32–bit, so the largest one is .Machine$integer.max =2,147,483,647= 2,147,483,647. Arithmetic between integers that exceeds this returns NA with a warning. This typically arises when n comes from length, dim or nrow, which return integers. For exact arithmetic beyond 2532^{53} the package bit64 (Chirico & Oehlschlägel, 2026) provides 64–bit integers.

    n <- dim(x)[1]         ## an integer, say 50000
    n * n                  ## NA with a warning
    as.numeric(n) * n      ## 2.5e9

8 Reading large–scale datasets

  1. For reading large text files, read.csv and read.table are slow: they read the file line by line and guess the type of every column. The function fread of the package data.table reads the file with multiple threads and is typically more than 10 times faster; read_csv of readr (Wickham et al., 2026) is a second option.

    x <- read.csv("data.csv")             ## classical
    x <- data.table::fread("data.csv")    ## much faster

9 Parallel computing in R

If we have a machine with more than one core, we can put them all to work simultaneously and speed up the process considerably. Combining this with the tricks above is even more beneficial.

The idea is to use a library that allows parallel computing. We make use of the built–in parallel package. Below are some instructions on how to use it. Several of our packages include parallel computing as an option, so if the notes below are not clear, one can always consult those functions. Suppose we are given a matrix with discrete data and wish to perform maximum likelihood estimation for the zero inflated Poisson distribution for each column of the given matrix. The relevant function (zip.mle) is available in the package Rfast (Papadakis et al., 2025).

n <- dim(x)[2]
res <- matrix(nrow = n, ncol = 4)
for ( i in 1:n )  res[i, ] <- unlist( Rfast::zip.mle(x[, i], 1e-6) )
colnames(res) <- c('iters', 'loglik', 'lambda', 'pi')

Using the parallel package the above code translates into the following.

cl <- makeCluster(ncores)  ## ncores is the number of cores to use
clusterExport(cl, "x")
clusterEvalQ(cl, library(Rfast))
res <- parSapply(cl, 1:n, function(i) unlist(Rfast::zip.mle(x[, i], 1e-6)))
stopCluster(cl)
res <- t(res)
colnames(res) <- c('iters', 'loglik', 'lambda', 'pi')
  1. On Linux and macOS, mclapply of the built–in package parallel package is often simpler and faster than a socket cluster: it forks the current R process, so the workers see all its objects without any copying or exporting, and there is no cluster to set up or stop.

    res <- parallel::mclapply(1:B, f, mc.cores = nc)  ## Linux / macOS

    The previous example for instance would be

    res_list <- mclapply(1:n, function(i) unlist(Rfast::zip.mle(x[, i], 1e-6)), 
    mc.cores = ncores)
    res <- do.call(rbind, res_list)
    colnames(res) <- c('iters', 'loglik', 'lambda', 'pi')  

10 Efficiently written functions in R packages

Multinomial regression is offered in the package VGAM (Yee, 2010), but also in the package nnet (Venables & Ripley, 2002). The implementation in the second package is much faster. The same is true for ordinal logistic regression in VGAM and in ordinal (Christensen, 2015); the latter is much faster. Also, the package fields (Nychka et al., 2015) has a function called rdist which is faster than the built–in dist. A fast implementation of the distance correlation is available in the package dcov (Weiqiang, 2020), and more memory– and computationally–efficient energy–related functions can be found in the package estats4 (Tsagris & Papadakis, 2026a). These are just some examples where a function is available in more than one package, but the implementations do not share the same computational cost.

Regression models, distance matrix computations, statistical tests, utility functions and many more can also be found in the packages Rfast (Papadakis et al., 2025) and Rfast2 (Papadakis et al., 2026). These two packages contain many fast or really fast functions, either written in C++ or written in R exploiting fast built–in functions. The packages matrixStats (Bengtsson, 2025) and collapse (Krantz, 2026) offer similar collections of row– and column–wise functions written in C or C++, and they complement each other.

11 More advanced programming tips

Some programming languages offer advanced features. We mention some of those that R supports, along with their strengths and benefits.

  1. Auto–printing our own class in our own style. In R we can print a variable using the functions print and cat, or by just typing the variable’s name and pressing enter. But what if we do not like the way R prints it? That is the point of auto–printing. R supports a general way to print our own class through its default function print. The method is very simple, with one requirement: we must change the class.

    print.new_class_name <- function(x, ...) {
      cat("auto-printing my variable with class 'new_class_name' 
      and value: ", x)
    }

    Example:

    1. Create a variable: x <- 0

    2. Change its class: class(x) <- "anything"

    3. Create the function to print the variable:

       print.anything <- function(x, ...) {
         cat("Auto-printing variable of class anything: ", x)
       }
    4. Type: print(x), or simply x.

    5. That’s it.

  2. Using if-else in one line. Another feature of C++ is the ternary operator (which cannot be overloaded). It is an if-else statement with a different syntax and one more capability: it returns the value of the selected branch, i.e. it is an if-else with assignment. R supports the same thing with its default if-else syntax, which can reduce the length of the code.
    Example:

      if ( is_true ) {
        x <- 1
      } else {
        x <- 2
      }

    The above example is very simple but needs 5 lines. Let us reduce it:

      x <- if (is_true)  1  else  2

    In a single line we have the same code. Be careful with the syntax, and make sure the last statement of each branch is the one we want to assign to x. For more than one command use curly brackets. This works because if-else in R is like a function that always returns its last evaluated expression, without the return keyword. Note: the same holds for if-else-if. This is a matter of style; there is no speed difference, since it is the same if construct.

  3. Iterating over a vector. If we want to iterate over a vector and use its elements, we can write:

      x <- rnorm(10)
      for ( i in seq_along(x) ) {
        cat(x[i])
      }

    This is the classic way. Another way is:

      x <- rnorm(10)
      for ( i in x ) {
        cat(i)
      }

    The second way is equivalent to the first, but instead of iterating over the indices we iterate over the elements themselves. This eliminates one indexing operation per element, i.e. length(x) operations in total. The gain is small though.

  4. Use "[[" instead of "$" for programmatic access to lists and data frames. The "$" operator performs partial matching on the name, which is a source of bugs in functions, and on data frames it dispatches to a method. "[[" matches exactly, takes the name as a variable, and is faster inside loops. The internal .subset2 does the same without any dispatch.

    x$val                 ## returns x$value if "val" is a unique prefix
    x[["value"]]          ## exact, and the name can be a variable
    .subset2(x, "value")  ## no dispatch at all

12 Conclusions

We have provided a long list of efficient coding tips to help the user make their programs faster. In some cases, the user can benefit from functions that use less memory, which is another important feature apart from speed. We also provided tips for avoiding numerical instabilities and overflows. These tips should not go unattended, as one can easily face such errors when trying to optimize the efficiency of their code.

Acknowledgements

We would like to thank Stefanos Fafalios, Christina Chatzipantsiou, Marco Maier, Panagiotis Tzirakis, Giorgos Athineou, Kleio Lakiotaki, Kurt Hornik, Uwe Ligges and the R Core team.

Conflicts of Interests

M. Tsagris and M. Papadakis are the maintainers of the R packages Rfast, Rfast2 and estats, which are recommended in this paper. The authors declare no other competing interests.

References

Cite this article

Tsagris, M., & Papadakis, M. (2026). Taking R to its limits: 90+ tips. Journal of Reproducible Statistics, 1, 15. https://doi.org/10.68365/jrepstat.2026.15

doi: https://doi.org/10.68365/jrepstat.2026.15

Downloads

PDF JATS XML .bib .ris .csl.json Reproducibility package (.zip) 7f0e4f414c71884cfddc967ffbf3a43fa57dc2ceb834cede6fe14f3dd3628dce

https://doi.org/10.68365/jrepstat.2026.15 also supports content negotiation, so reference managers can fetch the citation from the DOI directly. The exports above work without it.