<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN"
                  "JATS-archivearticle1.dtd">
<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="1.2" article-type="other">
<front>
<journal-meta>
<journal-id journal-id-type="publisher-id">jrepstat</journal-id>
<journal-title-group>
<journal-title>Journal of Reproducible Statistics</journal-title>
</journal-title-group>
<issn publication-format="electronic">3043-2790</issn>
<publisher>
<publisher-name>FAIR Press</publisher-name>
</publisher>
</journal-meta>
<article-meta>
<title-group>
<article-title>Taking R to its limits: 90+ tips</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<contrib-id contrib-id-type="orcid">https://orcid.org/0000-0002-2049-3063</contrib-id>
<name>
<surname>Tsagris</surname>
<given-names>Michail</given-names>
</name>
<aff>Department of Economics &amp; Institute of Research in Education and Digital Social Sciences and Humanities, University of Crete, Gallos Campus, Rethimno, Greece</aff>
</contrib>
<contrib contrib-type="author">
<name>
<surname>Papadakis</surname>
<given-names>Manos</given-names>
</name>
<aff>Independent researcher, Heraklion, Greece</aff>
</contrib>
</contrib-group>
<pub-date date-type="pub" publication-format="electronic">
<year>2026</year>
</pub-date>
<volume>1</volume>
<elocation-id>15</elocation-id>
<history>
<date date-type="received" iso-8601-date="2026-09-27"><day>27</day><month>09</month><year>2026</year></date>
<date date-type="accepted" iso-8601-date="2026-11-14"><day>14</day><month>11</month><year>2026</year></date>
</history>
<permissions>
<license license-type="open-access" xlink:href="https://creativecommons.org/licenses/by/4.0/">
<license-p>This is an open access article distributed under the terms of the Creative Commons Attribution 4.0 International License (CC-BY 4.0), which permits unrestricted use, distribution and reproduction in any medium provided the original work is properly cited.</license-p>
</license>
</permissions>
<self-uri content-type="html" xlink:href="https://jrepstat.fairpressjournals.com/articles/taking-r-to-its-limits-90-tips/"/>
<abstract>
<p>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.</p>
</abstract>
<kwd-group kwd-group-type="author">
<kwd>R programming</kwd>
<kwd>efficient code</kwd>
<kwd>statistical computing</kwd>
<kwd>vectorization</kwd>
<kwd>memory optimization</kwd>
<kwd>numerical stability</kwd>
</kwd-group>
<custom-meta-group>
<custom-meta>
<meta-name>data-availability-route</meta-name>
<meta-value>open</meta-value>
</custom-meta>
<custom-meta>
<meta-name>founding-article</meta-name>
<meta-value>true</meta-value>
</custom-meta>
</custom-meta-group>
</article-meta>
</front>
<body>
<sec id="introduction">
  <title><named-content content-type="header-section-number">1</named-content>
  Introduction</title>
  <p><italic>R</italic> 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 <italic>R</italic>
  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
  <ext-link ext-link-type="uri" xlink:href="https://www.burns-stat.com/pages/Tutor/R_inferno.pdf">The
  R Inferno</ext-link>, and Gillespie &amp; Lovelace (2016) gave a
  book–length treatment.</p>
  <p>We have listed 91 tips that can help the user write more efficient
  code, use less memory, and become more familiar with
  <italic>R</italic> 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 &amp; 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 <italic>R</italic> 4.6.1,
  and compared them to <italic>R</italic>’s built–in functions. We have
  not compared them to competing packages. In the uploaded
  <italic>R</italic> code we have added the session info of the
  <italic>R</italic> 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.</p>
  <p>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 <inline-formula><alternatives>
  <tex-math><![CDATA[1,000]]></tex-math>
  <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>1</mml:mn><mml:mo>,</mml:mo><mml:mn>000</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
  simulations, this amounts to <inline-formula><alternatives>
  <tex-math><![CDATA[5,000]]></tex-math>
  <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>5</mml:mn><mml:mo>,</mml:mo><mml:mn>000</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
  seconds. Our motto is that every decrease in time or memory
  matters.</p>
</sec>
<sec id="measuring-execution-time">
  <title><named-content content-type="header-section-number">2</named-content>
  Measuring execution time</title>
  <p>In order to measure the time a process, computation or simulation
  needs, we can do the following</p>
  <preformat>runtime &lt;- proc.time()
## put your function here
runtime &lt;- proc.time() - runtime
## runtime gives you 3 numbers (all in seconds) like the ones below
user  system elapsed 
0.18    0.07    3.35 </preformat>
  <p>The <monospace>elapsed</monospace> value is the desired metric.
  Alternatively, the package
  <named-content content-type="sans-serif">microbenchmark</named-content>
  (Mersmann, 2015) allows for the comparison of two or more functions,
  measuring their execution time even at the nanosecond scale. The
  package <named-content content-type="sans-serif">bench</named-content>
  (Hester &amp; Vaughan, 2025) does the same and also reports the memory
  allocated.</p>
</sec>
<sec id="general-advice">
  <title><named-content content-type="header-section-number">3</named-content>
  General advice</title>
  <p>We begin with a list of general programming advice.</p>
  <list list-type="order">
    <list-item>
      <p>When writing code, leave spaces between operations and
      parentheses, and indent the lines inside
      <monospace>for</monospace> 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 <italic>clean</italic>, 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.</p>
    </list-item>
    <list-item>
      <p>Profile before optimizing. We are usually wrong about where our
      code spends its time. <monospace>Rprof</monospace> interrupts
      <italic>R</italic> every 20 milliseconds (by default) and records
      which function is running; <monospace>summaryRprof</monospace>
      then reports the time spent in each function. Only the functions
      at the top of the list are worth optimizing.</p>
      <p specific-use="wrapper">
        <preformat>Rprof(&quot;prof.out&quot;)
## put your function here
Rprof(NULL)
summaryRprof(&quot;prof.out&quot;)$by.self
## profvis::profvis( your function ) gives the same 
## information as an interactive graph</preformat>
      </p>
      <p>The function below is a worked example of profiling. It appends
      to a vector inside a loop, sorts it and returns the mean.</p>
      <p specific-use="wrapper">
        <preformat>f &lt;- function(n) {
  x &lt;- NULL
  for ( i in 1:n )  x &lt;- c(x, sqrt(i))
  y &lt;- sort(x)
  sum(y) / length(y)
}
Rprof(&quot;prof.out&quot;, interval = 0.01)
a &lt;- f(1e5)
Rprof(NULL)
summaryRprof(&quot;prof.out&quot;)$by.self
             self.time self.pct total.time total.pct
&quot;c&quot;               5.31    99.81       5.31     99.81
&quot;Sys.getenv&quot;      0.01     0.19       0.01      0.19</preformat>
      </p>
      <p>Almost all the time is spent in <monospace>c()</monospace>,
      which copies the whole vector at every iteration. The sorting,
      which one might have suspected, is negligible. Preallocating
      removes the bottleneck.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- NULL
for ( i in 1:n )  x &lt;- c(x, sqrt(i))  ## not efficient
x &lt;- numeric(n)
for ( i in 1:n )  x[i] &lt;- sqrt(i)     ## efficient
x &lt;- sqrt(1:n)                        ## even better</preformat>
      </p>
    </list-item>
    <list-item>
      <p>Verify before trusting a speed–up. Every time a slow
      implementation is replaced by a faster one, compare them on the
      same input. Use <monospace>all.equal</monospace>, which allows for
      a small tolerance, and not <monospace>identical</monospace> or
      <monospace>==</monospace>, 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.</p>
      <p specific-use="wrapper">
        <preformat>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) ) &gt; tol )   ## correct
all.equal(fast(x), slow(x))                 ## TRUE, or a message </preformat>
      </p>
    </list-item>
    <list-item>
      <p>Avoid unnecessary calculations. In a discriminant analysis
      setting, for example, there is no need to calculate constant
      terms, such as <inline-formula><alternatives>
      <tex-math><![CDATA[\log{(2 \pi)}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mrow><mml:mi mathvariant="normal">log</mml:mi><mml:mo>&#8289;</mml:mo></mml:mrow><mml:mrow><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mn>2</mml:mn><mml:mi>π</mml:mi><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow></mml:mrow></mml:math></alternatives></inline-formula>,
      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.</p>
    </list-item>
    <list-item>
      <p>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.</p>
    </list-item>
    <list-item>
      <p>Suppose we have a function that uses many regression models,
      not necessarily from different downloadable <italic>R</italic>
      packages, but even from <italic>R</italic>’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: <monospace>lm</monospace> uses an
      <inline-formula><alternatives>
      <tex-math><![CDATA[F]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>F</mml:mi></mml:math></alternatives></inline-formula>
      test, <monospace>glm</monospace> uses an
      <inline-formula><alternatives>
      <tex-math><![CDATA[F]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>F</mml:mi></mml:math></alternatives></inline-formula>
      or a <inline-formula><alternatives>
      <tex-math><![CDATA[\chi^2]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mi>χ</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:math></alternatives></inline-formula>
      test, and so on.</p>
      <p>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.</p>
    </list-item>
    <list-item>
      <p>It is important to understand how <italic>R</italic> works,
      what operations do, and what we can and cannot do. The command
      <monospace>mahalanobis</monospace>, for example, uses the
      following line to calculate the distances.</p>
      <p specific-use="wrapper">
        <preformat>rowSums(x %*% cov * x)</preformat>
      </p>
      <p>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.</p>
    </list-item>
    <list-item>
      <p>If we have a vector <monospace>x</monospace> of integer
      numbers, it is preferable to store it as
      <monospace>as.integer(x)</monospace> rather than
      <monospace>as.numeric(x)</monospace>. The former requires 4 bytes
      per element, the latter 8.</p>
    </list-item>
    <list-item>
      <p>Copy–on–modify. When two names refer to the same object and one
      of them is modified, <italic>R</italic> silently copies the object
      first. Modifying a large object inside a function therefore
      duplicates it. The function <monospace>tracemem</monospace> prints
      a message every time an object is copied and is the simplest way
      to find unexpected copies.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- rnorm(1e7)
tracemem(x)
y &lt;- x        ## no copy yet, x and y share the same memory
y[1] &lt;- 0     ## now y is copied
x[1] &lt;- 0     ## no copy, x has a single reference</preformat>
      </p>
    </list-item>
    <list-item>
      <p>The byte–code compiler. The <monospace>compiler</monospace>
      package translates <italic>R</italic> functions into byte–code,
      which runs faster, especially for loops and scalar arithmetic.
      Since <italic>R</italic> 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.</p>
      <p specific-use="wrapper">
        <preformat>compiler::enableJIT(-1)   ## returns the current level, 3 = everything
f &lt;- compiler::cmpfun(f)  ## compile a function explicitly</preformat>
      </p>
      <p>Note that the compiler cannot vectorize a loop for us; the tips
      that follow remain necessary.</p>
    </list-item>
  </list>
</sec>
<sec id="simple-functions">
  <title><named-content content-type="header-section-number">4</named-content>
  Simple functions</title>
  <p>We continue with a list of simple functions that will help us make
  our code more efficient and faster.</p>
  <list list-type="order">
    <list-item>
      <label>11.</label>
      <p>Not all packages, or <italic>R</italic> itself, have the
      fastest implementations. The function <monospace>mean</monospace>
      is slower than <monospace>sum(x)/length(x)</monospace>, because
      <monospace>mean</monospace> 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
      <monospace>sum</monospace> is a <monospace>.Primitive</monospace>
      function, implemented directly in <italic>C</italic>, that
      performs a single pass. If we type <monospace>sum</monospace> we
      will see it is a <monospace>.Primitive</monospace> function,
      whereas <monospace>crossprod</monospace>, for example, is an
      <monospace>.Internal</monospace> 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 <italic>R</italic>’s built–in
      functions<xref ref-type="fn" rid="fn1">1</xref>.</p>
    </list-item>
    <list-item>
      <label>12.</label>
      <p>The commands <monospace>cor</monospace> and
      <monospace>cov</monospace> 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.</p>
    </list-item>
    <list-item>
      <label>13.</label>
      <p>Search for functions that take less time. For example,
      <monospace>lm(y </monospace><inline-formula><alternatives>
      <tex-math><![CDATA[\sim]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mo>∼</mml:mo></mml:math></alternatives></inline-formula><monospace> x)</monospace>
      calls <monospace>lm.fit(x, y)</monospace> after building the
      design matrix from the formula. If we only require the
      coefficients, we should use <monospace>lm.fit</monospace>
      directly. The syntax is a bit different, since
      <monospace>x</monospace> must be the design matrix, but the speed
      is also very different, especially in large cases. The command
      <monospace>.lm.fit(x, y)</monospace> is even faster.</p>
    </list-item>
    <list-item>
      <label>14.</label>
      <p>It’s your algorithm. Tsagris (2017) showed that conditional
      <inline-formula><alternatives>
      <tex-math><![CDATA[G^2]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mi>G</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:math></alternatives></inline-formula>
      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 <monospace>for</monospace>
      loops<xref ref-type="fn" rid="fn2">2</xref>. (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 <inline-formula><alternatives>
      <tex-math><![CDATA[t]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>t</mml:mi></mml:math></alternatives></inline-formula>–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.</p>
    </list-item>
    <list-item>
      <label>15.</label>
      <p>Suppose we want to center some data. We can try with
      <monospace>apply</monospace></p>
      <p specific-use="wrapper">
        <preformat>cent &lt;- function(x) x - mean(x)
a1 &lt;- apply(x, 2, cent)</preformat>
      </p>
      <p>or use one of the following alternatives</p>
      <p specific-use="wrapper">
        <preformat>a2 &lt;- scale(x, center = TRUE, scale = FALSE) 
m &lt;- colMeans(x)
a3 &lt;- sweep(x, 2L, m)
a4 &lt;- t( t(x) - m ) ## see the section on matrices
dm &lt;- dim(x)
n &lt;- dm[1]
p &lt;- dm[2]
a5 &lt;- x - rep( m, rep(n, p) ) </preformat>
      </p>
      <p>We generated a matrix with 10,000 rows and 20 columns. The time
      results using the package <italic>microbenchmark</italic> are as
      follows</p>
      <p specific-use="wrapper">
        <preformat>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</preformat>
      </p>
      <p>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.</p>
    </list-item>
    <list-item>
      <label>16.</label>
      <p>A very useful command is <monospace>tabulate</monospace>.</p>
      <p specific-use="wrapper">
        <preformat>table(iris[, 5])
tabulate(iris[, 5])</preformat>
      </p>
      <p>Two differences between them are that
      <monospace>table</monospace> returns the values as names, whereas
      <monospace>tabulate</monospace> returns only the frequencies.
      <monospace>tabulate</monospace> 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.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- rep(0:5, each = 4)
table(x)
tabulate(x)  ## 0 is missing
x &lt;- rep(c(1, 3, 4), each = 5)
table(x)
tabulate(x)  ## there is a 0 appearing indicating the absence of 2</preformat>
      </p>
      <p>The command <monospace>tabulate</monospace> is many times
      faster than <monospace>table</monospace>. For discriminant
      analysis algorithms <monospace>tabulate</monospace> 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 <monospace>tabulate</monospace>.</p>
    </list-item>
    <list-item>
      <label>17.</label>
      <p>To extract the mean vector of each group we can use a
      <monospace>for</monospace> loop or</p>
      <p specific-use="wrapper">
        <preformat>a1 &lt;- aggregate(x, by = list(ina), mean)</preformat>
      </p>
      <p>where <monospace>ina</monospace> is a numerical variable
      indicating the group. A faster alternative is the built–in command
      <monospace>rowsum</monospace></p>
      <p specific-use="wrapper">
        <preformat>a2 &lt;- rowsum(x, ina) / as.vector( table(ina) )
## a bit faster option is a3 below
a3 &lt;- rowsum(x, ina) / as.vector( tabulate(ina) )  </preformat>
      </p>
      <p>Note that this command works also for matrices. Note though
      that <monospace>tabulate</monospace> 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
      <named-content content-type="sans-serif">data.table</named-content>
      (Barrett et al., 2026)</p>
      <p specific-use="wrapper">
        <preformat>library(data.table)
dt &lt;- as.data.table(x)                  ## x is the numeric matrix
dt[, ina := ina]                        ## add the grouping variable
a1 &lt;- dt[, lapply(.SD, sum),  by = ina] ## group sums
a2 &lt;- dt[, lapply(.SD, mean), by = ina] ## group means</preformat>
      </p>
    </list-item>
    <list-item>
      <label>18.</label>
      <p>It is suggested to use <monospace>which.min(x)</monospace> and
      <monospace>which.max(x)</monospace> instead of
      <monospace>which( x == min(x) )</monospace> and
      <monospace>which( x == max(x) )</monospace> to find the position
      of the minimum and maximum, respectively. The former perform a
      single pass over the data, the latter two.</p>
    </list-item>
    <list-item>
      <label>19.</label>
      <p>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.</p>
    </list-item>
    <list-item>
      <label>20.</label>
      <p>When calculating operations such as
      <monospace>sum(a * x)</monospace>, where <monospace>x</monospace>
      is a vector or a matrix and <monospace>a</monospace> is a scalar,
      write <monospace>a * sum(x)</monospace>. The two are equal by the
      distributive law of multiplication over addition,
      <inline-formula><alternatives>
      <tex-math><![CDATA[\sum_{i=1}^n a x_i = a \sum_{i=1}^n x_i]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:msubsup><mml:mo>∑</mml:mo><mml:mrow><mml:mi>i</mml:mi><mml:mo>=</mml:mo><mml:mn>1</mml:mn></mml:mrow><mml:mi>n</mml:mi></mml:msubsup><mml:mi>a</mml:mi><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub><mml:mo>=</mml:mo><mml:mi>a</mml:mi><mml:msubsup><mml:mo>∑</mml:mo><mml:mrow><mml:mi>i</mml:mi><mml:mo>=</mml:mo><mml:mn>1</mml:mn></mml:mrow><mml:mi>n</mml:mi></mml:msubsup><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub></mml:mrow></mml:math></alternatives></inline-formula>,
      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.</p>
      <p specific-use="wrapper">
        <preformat>sum(a * x)  ## n multiplications and n-1 additions
a * sum(x)  ## n-1 additions and 1 multiplication</preformat>
      </p>
    </list-item>
    <list-item>
      <label>21.</label>
      <p>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
      <monospace>for</monospace> or a <monospace>while</monospace> loop,
      and hence we have to calculate the factorials repeatedly.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- rpois(10000, 5)
sum( lgamma(x + 1) )
y &lt;- sort( unique(x) )
ny &lt;- as.vector( table(x) )
sum( lgamma(y + 1) * ny )</preformat>
      </p>
    </list-item>
    <list-item>
      <label>22.</label>
      <p>If we use the <monospace>glm</monospace> or
      <monospace>lm</monospace> commands multiple times, then we should
      write</p>
      <p specific-use="wrapper">
        <preformat>glm(y ~ x, family = ..., y = FALSE, model = FALSE)
lm(y ~ x, y = FALSE, model = FALSE)</preformat>
      </p>
      <p>The two extra arguments
      <monospace>y = FALSE, model = FALSE</monospace> reduce the memory
      requirements of the fitted object.</p>
    </list-item>
    <list-item>
      <label>23.</label>
      <p>When calculating <inline-formula><alternatives>
      <tex-math><![CDATA[\log{\left(1+x\right)}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mrow><mml:mi mathvariant="normal">log</mml:mi><mml:mo>&#8289;</mml:mo></mml:mrow><mml:mrow><mml:mo stretchy="true" form="prefix">(</mml:mo><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="true" form="postfix">)</mml:mo></mml:mrow></mml:mrow></mml:math></alternatives></inline-formula>
      use <monospace>log1p(x)</monospace> instead of
      <monospace>log(1 + x)</monospace>. The advantage is accuracy: when
      <inline-formula><alternatives>
      <tex-math><![CDATA[x]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>x</mml:mi></mml:math></alternatives></inline-formula>
      is very small, <inline-formula><alternatives>
      <tex-math><![CDATA[1 + x]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:mi>x</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
      is rounded to 1 and <monospace>log(1 + x)</monospace> returns 0,
      whereas <monospace>log1p(x)</monospace> returns the correct value.
      The same holds for <inline-formula><alternatives>
      <tex-math><![CDATA[e^x - 1]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:msup><mml:mi>e</mml:mi><mml:mi>x</mml:mi></mml:msup><mml:mo>−</mml:mo><mml:mn>1</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
      and <monospace>expm1(x)</monospace>.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- 1e-17
log(1 + x)   ## 0
log1p(x)     ## 1e-17</preformat>
      </p>
    </list-item>
    <list-item>
      <label>24.</label>
      <p>Vectorization can save a tremendous amount of time even in
      small datasets. Try to avoid <monospace>for</monospace> loops by
      using vectorized operations or matrix multiplications. For
      example, instead of</p>
      <p specific-use="wrapper">
        <preformat>for (i in 1:n) y[i] &lt;- x[i]^2</preformat>
      </p>
      <p>we can write</p>
      <p specific-use="wrapper">
        <preformat>y &lt;- x^2</preformat>
      </p>
      <p>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.</p>
    </list-item>
    <list-item>
      <label>25.</label>
      <p>A useful command is <monospace>outer</monospace>. An example is
      where we have two vectors <monospace>x</monospace> and
      <monospace>y</monospace> and we want to add each element of
      <monospace>y</monospace> to each element of
      <monospace>x</monospace>. The result is a matrix.</p>
      <p specific-use="wrapper">
        <preformat>z &lt;- matrix(0, nrow = length(x), ncol = length(y) )
for ( i in 1:dim(z)[1] )  z[i, ] &lt;- x[i] + y
## The above task can take place a lot faster by typing 
outer(x, y, &quot;+&quot;)</preformat>
      </p>
    </list-item>
    <list-item>
      <label>26.</label>
      <p>The command <monospace>sort</monospace> has an extra feature:
      by specifying <monospace>index.return = TRUE</monospace>, the
      outcome is a list with the sorted numbers along with their
      ordering indices. That is,
      <monospace>sort(x, index.return = TRUE)</monospace> sorts the
      numbers and returns their order as if we had used
      <monospace>order</monospace> separately.</p>
    </list-item>
    <list-item>
      <label>27.</label>
      <p>We can partially sort a vector. In the
      <inline-formula><alternatives>
      <tex-math><![CDATA[k]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>k</mml:mi></mml:math></alternatives></inline-formula>–<inline-formula><alternatives>
      <tex-math><![CDATA[NN]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>N</mml:mi><mml:mi>N</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
      algorithm, for example, we want the <inline-formula><alternatives>
      <tex-math><![CDATA[k]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>k</mml:mi></mml:math></alternatives></inline-formula>
      smallest distances. There is no need to sort all the distances,
      only the <inline-formula><alternatives>
      <tex-math><![CDATA[k]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>k</mml:mi></mml:math></alternatives></inline-formula>
      smallest: <monospace>sort(x, partial = 1:k)</monospace>.</p>
    </list-item>
    <list-item>
      <label>28.</label>
      <p>Many functions call internal functions.
      <monospace>sort</monospace>, for example, calls
      <monospace>sort.int</monospace>, and <monospace>sample</monospace>
      calls <monospace>sample.int</monospace>. Calling the internal
      function directly avoids the argument checking of the wrapper.</p>
    </list-item>
    <list-item>
      <label>29.</label>
      <p>Suppose we are given many matrices in a list,
      <monospace>A</monospace>, and wish to stack them one under the
      other into a new matrix. The command to do this efficiently is</p>
      <p specific-use="wrapper">
        <preformat>do.call(rbind, A)</preformat>
      </p>
    </list-item>
    <list-item>
      <label>30.</label>
      <p>Use <monospace>seq_len(n)</monospace> instead of
      <monospace>1:n</monospace> and <monospace>seq_along(x)</monospace>
      instead of <monospace>1:length(x)</monospace> in loops. When
      <monospace>n</monospace> is 0, <monospace>1:n</monospace> is
      <monospace>c(1, 0)</monospace> and the loop runs twice on
      non–existent elements, whereas <monospace>seq_len(0)</monospace>
      is empty and the loop is skipped.</p>
      <p specific-use="wrapper">
        <preformat>for ( i in 1:length(x) )    ## fails when x is empty
for ( i in seq_along(x) )   ## correct</preformat>
      </p>
    </list-item>
    <list-item>
      <label>31.</label>
      <p>Use <monospace>vapply</monospace> instead of
      <monospace>sapply</monospace> when the function returns a value of
      known type and length. <monospace>sapply</monospace> inspects all
      the results in order to decide what to return, whereas
      <monospace>vapply</monospace> is told in advance, allocates the
      result once, and fails if a result has the wrong type.</p>
      <p specific-use="wrapper">
        <preformat>sapply(x, f)               ## classical
vapply(x, f, numeric(1))   ## more efficient and safer</preformat>
      </p>
    </list-item>
    <list-item>
      <label>32.</label>
      <p>Use <monospace>anyNA(x)</monospace> instead of
      <monospace>any(is.na(x))</monospace>. The latter allocates a
      logical vector of the same length as <monospace>x</monospace> and
      scans it entirely, whereas the former stops at the first missing
      value.</p>
      <p specific-use="wrapper">
        <preformat>any( is.na(x) )  ## classical
anyNA(x)         ## more efficient</preformat>
      </p>
    </list-item>
    <list-item>
      <label>33.</label>
      <p>When flattening a list with <monospace>unlist</monospace>, drop
      the names if they are not needed. Constructing the names is often
      more expensive than the flattening itself.</p>
      <p specific-use="wrapper">
        <preformat>unlist(x)                     ## classical
unlist(x, use.names = FALSE)  ## more efficient</preformat>
      </p>
    </list-item>
    <list-item>
      <label>34.</label>
      <p>The vectorized <monospace>ifelse</monospace> evaluates both
      branches in full and carries a large overhead. For a scalar
      condition use <monospace>if-else</monospace>, and for numeric
      vectors use arithmetic on the logical condition.</p>
      <p specific-use="wrapper">
        <preformat>ifelse(test, 1, 2)             ## slow for a scalar test
if (test) 1 else 2             ## efficient
ifelse(x &gt; 0, x, 0)            ## classical
x * (x &gt; 0)                    ## more efficient</preformat>
      </p>
      <p>Note however, that these two differ when x contains NA, so
      users should not swap them blindly.</p>
    </list-item>
    <list-item>
      <label>35.</label>
      <p>For binning a numerical vector into intervals use
      <monospace>findInterval</monospace> instead of
      <monospace>cut</monospace>. <monospace>cut</monospace> constructs
      a factor with character labels, whereas
      <monospace>findInterval</monospace> returns the integer index of
      the interval directly, which is what is usually needed afterwards
      (for <monospace>tabulate</monospace> or
      <monospace>rowsum</monospace>).</p>
      <p specific-use="wrapper">
        <preformat>as.integer( cut(x, breaks) )   ## classical
findInterval(x, breaks)        ## more efficient</preformat>
      </p>
    </list-item>
  </list>
</sec>
<sec id="calculations-involving-matrices">
  <title><named-content content-type="header-section-number">5</named-content>
  Calculations involving matrices</title>
  <p><italic>R</italic> is not designed to handle large–scale datasets,
  yet there are many ways to handle matrices efficiently, and we present
  some tricks below.</p>
  <list list-type="order">
    <list-item>
      <label>36.</label>
      <p>Use <monospace>colMeans</monospace>,
      <monospace>rowMeans</monospace>, <monospace>colSums</monospace>
      and <monospace>rowSums</monospace> instead of
      <monospace>apply(x, 2, mean)</monospace>,
      <monospace>apply(x, 1, mean)</monospace>, etc., as they are
      extremely fast. In addition, many really fast functions can be
      built using these commands. In general, we should avoid
      <monospace>apply</monospace> and <monospace>aggregate</monospace>
      whenever possible. For the median, though, there is no built–in
      alternative, and <monospace>apply(x, 2, median)</monospace> should
      be used instead of a <monospace>for</monospace> loop going through
      every column of the matrix. The <monospace>for</monospace> loop is
      not slower, but the <monospace>apply</monospace> is neater.</p>
    </list-item>
    <list-item>
      <label>37.</label>
      <p>In the same spirit as <monospace>.lm.fit</monospace>, the
      functions <monospace>.colSums</monospace>,
      <monospace>.rowSums</monospace>, <monospace>.colMeans</monospace>
      and <monospace>.rowMeans</monospace> are the internal versions of
      <monospace>colSums</monospace> 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.</p>
      <p specific-use="wrapper">
        <preformat>colSums(x)               ## classical
.colSums(x, n, p)        ## more efficient inside loops</preformat>
      </p>
    </list-item>
    <list-item>
      <label>38.</label>
      <p>If we have to use a <monospace>for</monospace> loop going
      through the rows of a matrix, consider transposing the matrix and
      then going through its columns.</p>
    </list-item>
    <list-item>
      <label>39.</label>
      <p>If we are given a matrix and, inside a
      <monospace>for</monospace> loop, we would like to extract some
      specific columns/rows each time, we can instead store the indices
      of the columns/rows inside the <monospace>for</monospace> loop
      and, outside the loop, extract the columns/rows once and perform
      the operations we want.</p>
    </list-item>
    <list-item>
      <label>40.</label>
      <p>If we want the number of rows or columns of a matrix
      <bold>X</bold>, we should not use <monospace>nrow(X)</monospace>
      or <monospace>ncol(X)</monospace>, but
      <monospace>dim(X)[1]</monospace> or
      <monospace>dim(X)[2]</monospace>, as they are roughly 2 times
      faster. <monospace>nrow</monospace> and
      <monospace>ncol</monospace> are <italic>R</italic>–level functions
      that call <monospace>dim</monospace> 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.</p>
    </list-item>
    <list-item>
      <label>41.</label>
      <p>Suppose we have a matrix <bold>X</bold> and we want the
      position of the maximum for each row. The obvious solution is
      <monospace>apply(X, 1, which.max)</monospace>. The efficient
      solution is <monospace>max.col(X)</monospace>. Note that by
      default <monospace>max.col</monospace> breaks ties at random; use
      <monospace>max.col(X, ties.method = &quot;first&quot;)</monospace>
      to obtain the same result as <monospace>which.max</monospace>.</p>
    </list-item>
    <list-item>
      <label>42.</label>
      <p>If we want to subtract a vector from a matrix in a row–wise
      fashion, we should be aware of the fact that <italic>R</italic>
      does it column–wise. This is because <italic>R</italic> reads,
      writes and stores data in a column–wise fashion. For example, let
      <bold>X</bold> be a matrix and <bold>y</bold> a vector whose
      length is equal to the number of columns of <bold>X</bold>. We
      should type</p>
      <p specific-use="wrapper">
        <preformat>t(X) - y</preformat>
      </p>
    </list-item>
    <list-item>
      <label>43.</label>
      <p>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 <bold>X</bold>, we should type</p>
      <p specific-use="wrapper">
        <preformat>Y &lt;- t(X)  ## not suggested
X &lt;- t(X)  ## suggested</preformat>
      </p>
      <p>We repeat that this applies only when <monospace>X</monospace>
      is not used again in later steps. The reason is memory saving: if
      <monospace>X</monospace> is big and we keep a second object as big
      as the first one, we request extra memory for no reason.</p>
    </list-item>
    <list-item>
      <label>44.</label>
      <p>Use the command <monospace>princomp</monospace> instead of
      <monospace>prcomp</monospace> for principal component
      analysis<xref ref-type="fn" rid="fn3">3</xref>. We generated a
      matrix with 10,000 rows and 50 columns to benchmark this and the
      results are presented below.</p>
      <p specific-use="wrapper">
        <preformat>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</preformat>
      </p>
    </list-item>
    <list-item>
      <label>45.</label>
      <p>Create vectors or matrices of the required size from the start.
      Instead of making a vector longer each time using
      <monospace>c()</monospace>, create an empty vector with the
      required size. The commands <monospace>rbind</monospace> and
      <monospace>cbind</monospace> 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).</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- numeric(n)          ## vector of n zeros
x &lt;- integer(n)          ## integer vector
x &lt;- matrix(0, n, p)     ## n x p matrix
x &lt;- vector(&quot;list&quot;, n)   ## list of n NULLs</preformat>
      </p>
    </list-item>
    <list-item>
      <label>46.</label>
      <p>For group covariance matrices the command
      <monospace>by</monospace> could be used. The matrices are stored
      in a list and the command <monospace>simplify2array</monospace> is
      then needed to convert the list to an array, in order to
      calculate, for example, the determinant of each matrix. A
      <monospace>for</monospace> loop is faster.</p>
    </list-item>
    <list-item>
      <label>47.</label>
      <p>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
      <monospace>apply(x, 1:2, mean)</monospace>. Since
      <italic>R</italic> works column–wise, we can instead use
      <monospace>t( colSums( aperm(x) ) )</monospace> and
      <monospace>t( colMeans( aperm(x) ) )</monospace> for the sum and
      the mean, respectively.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- array( dim = c(1000, 10, 10) )
for (i in 1:10) x[, , i] &lt;- matrix( rnorm(1000 * 10), ncol = 10 )
a1 &lt;- apply(x, 1:2, mean)
a2 &lt;- t( colMeans( aperm(x) ) ) </preformat>
      </p>
    </list-item>
    <list-item>
      <label>48.</label>
      <p>If we want to calculate the logarithm of the determinant of a
      matrix <bold>X</bold>, instead of
      <monospace>log( det(X) )</monospace> we can type
      <monospace>determinant(X, logarithm = TRUE)</monospace>, as it is
      slightly faster for small matrices. For big matrices, say of
      dimensions <inline-formula><alternatives>
      <tex-math><![CDATA[100 \times 100]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>100</mml:mn><mml:mo>×</mml:mo><mml:mn>100</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
      or more, the difference becomes negligible.</p>
    </list-item>
    <list-item>
      <label>49.</label>
      <p>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.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- rnorm(50)
y &lt;- matrix( rnorm(1000 * 50), ncol = 50 )
a1 &lt;- dist( rbind(x, y) )  ## inefficient way
Ip &lt;- diag(50)
                           ## below is a better way
a2 &lt;- sqrt( mahalanobis( y, center = x, cov = Ip, inverted = TRUE ) )</preformat>
      </p>
      <p>Another way is the following</p>
      <p specific-use="wrapper">
        <preformat>z &lt;- t(y) - x              ## R recycles column--wise
a3 &lt;- sqrt( colSums(z^2) )</preformat>
      </p>
    </list-item>
    <list-item>
      <label>50.</label>
      <p>Calculating <inline-formula><alternatives>
      <tex-math><![CDATA[{\textbf{X}}^\top{\textbf{Y}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:msup><mml:mtext mathvariant="bold">𝐗</mml:mtext><mml:mi>⊤</mml:mi></mml:msup><mml:mtext mathvariant="bold">𝐘</mml:mtext></mml:mrow></mml:math></alternatives></inline-formula>
      as <monospace>t(X) %*% Y</monospace> instead of
      <monospace>crossprod(X, Y)</monospace> forces <italic>R</italic>
      to allocate a transposed copy of <bold>X</bold> before the
      multiplication, whereas <monospace>crossprod</monospace> 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.</p>
    </list-item>
    <list-item>
      <label>51.</label>
      <p>Similarly, the product <inline-formula><alternatives>
      <tex-math><![CDATA[{\textbf{X}}^\top{\textbf{X}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:msup><mml:mtext mathvariant="bold">𝐗</mml:mtext><mml:mi>⊤</mml:mi></mml:msup><mml:mtext mathvariant="bold">𝐗</mml:mtext></mml:mrow></mml:math></alternatives></inline-formula>
      of an <inline-formula><alternatives>
      <tex-math><![CDATA[n \times p]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>n</mml:mi><mml:mo>×</mml:mo><mml:mi>p</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
      matrix is computed faster by <monospace>crossprod(X)</monospace>
      than by the explicit matrix multiplication, since the result is
      known to be symmetric.</p>
      <p specific-use="wrapper">
        <preformat>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</preformat>
      </p>
    </list-item>
    <list-item>
      <label>52.</label>
      <p>Let <inline-formula><alternatives>
      <tex-math><![CDATA[\mathbf{X}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="bold-italic">𝑿</mml:mi></mml:math></alternatives></inline-formula>
      and <inline-formula><alternatives>
      <tex-math><![CDATA[\mathbf{m}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="bold-italic">𝒎</mml:mi></mml:math></alternatives></inline-formula>
      be a matrix and a vector, and suppose we want the sum of their
      elementwise product. There are two ways to do it.</p>
      <p specific-use="wrapper">
        <preformat>sum(m * t(x))  
sum(x %*% m)  ## more than 2 times faster</preformat>
      </p>
    </list-item>
    <list-item>
      <label>53.</label>
      <p>When working with arrays it is more efficient to have them
      transposed. For example, if we have <inline-formula><alternatives>
      <tex-math><![CDATA[K]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>K</mml:mi></mml:math></alternatives></inline-formula>
      covariance matrices of dimension <inline-formula><alternatives>
      <tex-math><![CDATA[p \times p]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>p</mml:mi><mml:mo>×</mml:mo><mml:mi>p</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>,
      we would naturally create an array of dimensions
      <monospace>c(p, p, K)</monospace>. Make its dimensions
      <monospace>c(K, p, p)</monospace> instead. If we want, for
      example, to divide each matrix by a different scalar, in the first
      case we have to use a <monospace>for</monospace> loop, whereas in
      the transposed case we simply divide the array by the vector of
      scalars.</p>
    </list-item>
    <list-item>
      <label>54.</label>
      <p>If we want to invert a positive definite matrix (e.g. a
      covariance matrix) we should use
      <monospace>chol2inv( chol( X ) )</monospace>, as it is faster than
      <monospace>solve(X)</monospace>.</p>
    </list-item>
    <list-item>
      <label>55.</label>
      <p>To invert a matrix (not necessarily positive definite) and
      multiply the result with a vector or another matrix, there are two
      ways</p>
      <p specific-use="wrapper">
        <preformat>solve(X) %*% Y  ## classical
## a much more efficient way is to not invert the matrix X
solve(X, Y)   </preformat>
      </p>
    </list-item>
    <list-item>
      <label>56.</label>
      <p>The quantity <inline-formula><alternatives>
      <tex-math><![CDATA[\text{tr}\left({\textbf{X}}^\top{\textbf{X}}\right)]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mtext mathvariant="normal">tr</mml:mtext><mml:mrow><mml:mo stretchy="true" form="prefix">(</mml:mo><mml:msup><mml:mtext mathvariant="bold">𝐗</mml:mtext><mml:mi>⊤</mml:mi></mml:msup><mml:mtext mathvariant="bold">𝐗</mml:mtext><mml:mo stretchy="true" form="postfix">)</mml:mo></mml:mrow></mml:mrow></mml:math></alternatives></inline-formula>
      can be evaluated either via</p>
      <p specific-use="wrapper">
        <preformat>sum( diag( crossprod(X) ) )  </preformat>
      </p>
      <p>or, faster, via</p>
      <p specific-use="wrapper">
        <preformat>sum(X * X) ## or 
sum(X^2)   </preformat>
      </p>
      <p>Note that for a square matrix <inline-formula><alternatives>
      <tex-math><![CDATA[\text{tr}\left({\textbf{X}}^2\right)]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mtext mathvariant="normal">tr</mml:mtext><mml:mrow><mml:mo stretchy="true" form="prefix">(</mml:mo><mml:msup><mml:mtext mathvariant="bold">𝐗</mml:mtext><mml:mn>2</mml:mn></mml:msup><mml:mo stretchy="true" form="postfix">)</mml:mo></mml:mrow></mml:mrow></mml:math></alternatives></inline-formula>
      is a different quantity, equal to
      <monospace>sum(X * t(X))</monospace>.</p>
    </list-item>
    <list-item>
      <label>57.</label>
      <p>Similarly, the trace <inline-formula><alternatives>
      <tex-math><![CDATA[\text{tr}\left({\textbf{X}}^\top{\textbf{Y}}\right)]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mtext mathvariant="normal">tr</mml:mtext><mml:mrow><mml:mo stretchy="true" form="prefix">(</mml:mo><mml:msup><mml:mtext mathvariant="bold">𝐗</mml:mtext><mml:mi>⊤</mml:mi></mml:msup><mml:mtext mathvariant="bold">𝐘</mml:mtext><mml:mo stretchy="true" form="postfix">)</mml:mo></mml:mrow></mml:mrow></mml:math></alternatives></inline-formula>
      can be computed either via</p>
      <p specific-use="wrapper">
        <preformat>sum( diag( crossprod(X, Y) ) )  ## just like before</preformat>
      </p>
      <p>or, faster, via</p>
      <p specific-use="wrapper">
        <preformat>sum(X * Y)  ## faster, like before</preformat>
      </p>
    </list-item>
    <list-item>
      <label>58.</label>
      <p>In the same spirit, if we want the diagonal of the product of
      two matrices, type</p>
      <p specific-use="wrapper">
        <preformat>diag( tcrossprod(X, Y) )  ## for example
rowSums(X * Y)            ## this is faster</preformat>
      </p>
    </list-item>
    <list-item>
      <label>59.</label>
      <p>Suppose we have two matrices <inline-formula><alternatives>
      <tex-math><![CDATA[\mathbf{A}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="bold-italic">𝑨</mml:mi></mml:math></alternatives></inline-formula>,
      <inline-formula><alternatives>
      <tex-math><![CDATA[\mathbf{B}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="bold-italic">𝑩</mml:mi></mml:math></alternatives></inline-formula>
      and a vector <inline-formula><alternatives>
      <tex-math><![CDATA[\mathbf{x}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="bold-italic">𝒙</mml:mi></mml:math></alternatives></inline-formula>
      and we want <inline-formula><alternatives>
      <tex-math><![CDATA[\mathbf{ABx}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi mathvariant="bold-italic">𝑨</mml:mi><mml:mi mathvariant="bold-italic">𝑩</mml:mi><mml:mi mathvariant="bold-italic">𝒙</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
      (the dimensions must match, of course).</p>
      <p specific-use="wrapper">
        <preformat>A %*% B %*% x    ## inefficient way
A %*% (B %*% x)  ## efficient way</preformat>
      </p>
      <p>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.</p>
    </list-item>
    <list-item>
      <label>60.</label>
      <p>For the reconstruction of a matrix from its eigendecomposition,
      there are two ways to do the multiplication</p>
      <p specific-use="wrapper">
        <preformat>s &lt;- matrix( rnorm(100 * 100), ncol = 100 )
s &lt;- crossprod(s)
eig &lt;- eigen(s)
vec &lt;- eig$vectors
lam &lt;- eig$values
a1 &lt;- vec %*% diag(lam) %*% t(vec) 
a2 &lt;- vec %*% ( t(vec) * lam )  ## faster way</preformat>
      </p>
    </list-item>
    <list-item>
      <label>61.</label>
      <p>The exponential term of the multivariate normal density can be
      calculated either using matrices or simply with the command
      <monospace>mahalanobis</monospace>. If we have many observations,
      many dimensions, or many groups, this can save a <bold>lot</bold>
      of time.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- matrix( rnorm(1000 * 20), ncol = 20 )
m &lt;- colMeans(x)
dm &lt;- dim(x)
n &lt;- dm[1]
p &lt;- dm[2]
s &lt;- cov(x) 
a1 &lt;- diag( (x - rep(m, rep(n, p)) ) %*% solve(s) 
            %*% t(x - rep(m, rep(n, p)) ) ) 
a2 &lt;- diag( t( t(x) - m ) %*% solve(s) %*% ( t(x) - m ) ) 
a3 &lt;- mahalanobis(x, m, s)  ## much faster</preformat>
      </p>
    </list-item>
    <list-item>
      <label>62.</label>
      <p>Suppose we want to compute the trace of the square of the
      correlation matrix <inline-formula><alternatives>
      <tex-math><![CDATA[{\textbf{R}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mtext mathvariant="bold">𝐑</mml:mtext></mml:math></alternatives></inline-formula>.
      It is well known from linear algebra (Strang, 2023) that for a
      symmetric matrix <inline-formula><alternatives>
      <tex-math><![CDATA[\mathbf{A}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="bold-italic">𝑨</mml:mi></mml:math></alternatives></inline-formula>,
      its eigendecomposition is given by <inline-formula><alternatives>
      <tex-math><![CDATA[{\textbf{A}}=\bm{\Gamma}\bm{\Lambda}\bm{\Gamma}^\top]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mtext mathvariant="bold">𝐀</mml:mtext><mml:mo>=</mml:mo><mml:mi mathvariant="bold">𝚪</mml:mi><mml:mi mathvariant="bold">𝚲</mml:mi><mml:msup><mml:mi mathvariant="bold">𝚪</mml:mi><mml:mi>⊤</mml:mi></mml:msup></mml:mrow></mml:math></alternatives></inline-formula>,
      where <inline-formula><alternatives>
      <tex-math><![CDATA[\bm{\Gamma}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="bold">𝚪</mml:mi></mml:math></alternatives></inline-formula>
      is the matrix of eigenvectors and <inline-formula><alternatives>
      <tex-math><![CDATA[\bm{\Lambda}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="bold">𝚲</mml:mi></mml:math></alternatives></inline-formula>
      is a diagonal matrix that contains the
      <inline-formula><alternatives>
      <tex-math><![CDATA[p]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>p</mml:mi></mml:math></alternatives></inline-formula>
      eigenvalues <inline-formula><alternatives>
      <tex-math><![CDATA[\lambda_1,\ldots,\lambda_p]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:msub><mml:mi>λ</mml:mi><mml:mn>1</mml:mn></mml:msub><mml:mo>,</mml:mo><mml:mi>…</mml:mi><mml:mo>,</mml:mo><mml:msub><mml:mi>λ</mml:mi><mml:mi>p</mml:mi></mml:msub></mml:mrow></mml:math></alternatives></inline-formula>.
      Note that <inline-formula><alternatives>
      <tex-math><![CDATA[\text{tr}({\textbf{A}})=\sum_{j=1}^p\lambda_j]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mtext mathvariant="normal">tr</mml:mtext><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mtext mathvariant="bold">𝐀</mml:mtext><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>=</mml:mo><mml:msubsup><mml:mo>∑</mml:mo><mml:mrow><mml:mi>j</mml:mi><mml:mo>=</mml:mo><mml:mn>1</mml:mn></mml:mrow><mml:mi>p</mml:mi></mml:msubsup><mml:msub><mml:mi>λ</mml:mi><mml:mi>j</mml:mi></mml:msub></mml:mrow></mml:math></alternatives></inline-formula>
      and <inline-formula><alternatives>
      <tex-math><![CDATA[\text{tr}({\textbf{A}}^2)=\sum_{j=1}^p\lambda_j^2]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mtext mathvariant="normal">tr</mml:mtext><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:msup><mml:mtext mathvariant="bold">𝐀</mml:mtext><mml:mn>2</mml:mn></mml:msup><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>=</mml:mo><mml:msubsup><mml:mo>∑</mml:mo><mml:mrow><mml:mi>j</mml:mi><mml:mo>=</mml:mo><mml:mn>1</mml:mn></mml:mrow><mml:mi>p</mml:mi></mml:msubsup><mml:msubsup><mml:mi>λ</mml:mi><mml:mi>j</mml:mi><mml:mn>2</mml:mn></mml:msubsup></mml:mrow></mml:math></alternatives></inline-formula>.
      This trick allows us to avoid computing the correlation matrix,
      multiplying it by itself and then summing its diagonal
      elements.</p>
      <p><italic>R</italic>’s built–in function
      <monospace>prcomp()</monospace> 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
      <inline-formula><alternatives>
      <tex-math><![CDATA[p]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>p</mml:mi></mml:math></alternatives></inline-formula>
      eigenvectors and <inline-formula><alternatives>
      <tex-math><![CDATA[p]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>p</mml:mi></mml:math></alternatives></inline-formula>
      eigenvalues, when in fact at most <inline-formula><alternatives>
      <tex-math><![CDATA[n-1]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>n</mml:mi><mml:mo>−</mml:mo><mml:mn>1</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
      eigenvalues are non–zero, since the rank of the correlation matrix
      is at most <inline-formula><alternatives>
      <tex-math><![CDATA[n-1]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>n</mml:mi><mml:mo>−</mml:mo><mml:mn>1</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
      when <inline-formula><alternatives>
      <tex-math><![CDATA[n<p]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>n</mml:mi><mml:mo>&lt;</mml:mo><mml:mi>p</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>.
      Hence, instead of <monospace>prcomp()</monospace>, the function
      <monospace>hd.eigen()</monospace> available in
      <italic>Rfast</italic> can be applied. This function is optimized
      for the case <inline-formula><alternatives>
      <tex-math><![CDATA[n<p]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>n</mml:mi><mml:mo>&lt;</mml:mo><mml:mi>p</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
      and returns the first <inline-formula><alternatives>
      <tex-math><![CDATA[n]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>n</mml:mi></mml:math></alternatives></inline-formula>
      eigenvectors and eigenvalues. Thus,
      <monospace>hd.eigen()</monospace> is not only faster than
      <monospace>prcomp()</monospace> in high–dimensional settings, but
      also requires less memory. The function takes the original data
      (<inline-formula><alternatives>
      <tex-math><![CDATA[{\textbf{Y}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mtext mathvariant="bold">𝐘</mml:mtext></mml:math></alternatives></inline-formula>),
      standardizes them (<inline-formula><alternatives>
      <tex-math><![CDATA[{\textbf{Z}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mtext mathvariant="bold">𝐙</mml:mtext></mml:math></alternatives></inline-formula>),
      and performs the eigendecomposition of the matrix
      <inline-formula><alternatives>
      <tex-math><![CDATA[{\textbf{ZZ}}^\top]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mtext mathvariant="bold">𝐙𝐙</mml:mtext><mml:mi>⊤</mml:mi></mml:msup></mml:math></alternatives></inline-formula>.
      The sum of the squared eigenvalues divided by
      <inline-formula><alternatives>
      <tex-math><![CDATA[(n-1)^2]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>n</mml:mi><mml:mo>−</mml:mo><mml:mn>1</mml:mn><mml:msup><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mn>2</mml:mn></mml:msup></mml:mrow></mml:math></alternatives></inline-formula>
      equals <inline-formula><alternatives>
      <tex-math><![CDATA[\text{tr}({\textbf{R}}^2)]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mtext mathvariant="normal">tr</mml:mtext><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:msup><mml:mtext mathvariant="bold">𝐑</mml:mtext><mml:mn>2</mml:mn></mml:msup><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow></mml:math></alternatives></inline-formula>.</p>
    </list-item>
    <list-item>
      <label>63.</label>
      <p>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.</p>
      <p specific-use="wrapper">
        <preformat>for (i in 1:n)  f( df[i, ] )    ## very slow
x &lt;- as.matrix(df)
for (i in 1:n)  f( x[i, ] )     ## much faster</preformat>
      </p>
    </list-item>
    <list-item>
      <label>64.</label>
      <p>Use <monospace>drop = FALSE</monospace> when subsetting
      matrices. By default <monospace>X[, 1]</monospace> returns a
      vector, so a function that extracts
      <monospace>X[, ind]</monospace> will silently receive a vector
      when <monospace>ind</monospace> has length 1, and
      <monospace>dim</monospace> or <monospace>colSums</monospace> will
      fail. This tip is about correctness rather than speed.</p>
      <p specific-use="wrapper">
        <preformat>X[, ind]                ## vector when length(ind) == 1
X[, ind, drop = FALSE]  ## always a matrix</preformat>
      </p>
    </list-item>
    <list-item>
      <label>65.</label>
      <p>If a linear system involves a triangular matrix, e.g. the
      Cholesky factor of a covariance matrix, do not use
      <monospace>solve</monospace>, which treats the matrix as a general
      one. <monospace>backsolve</monospace> and
      <monospace>forwardsolve</monospace> exploit the triangular
      structure and solve the system in <inline-formula><alternatives>
      <tex-math><![CDATA[O(p^2)]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>O</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:msup><mml:mi>p</mml:mi><mml:mn>2</mml:mn></mml:msup><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow></mml:math></alternatives></inline-formula>
      instead of <inline-formula><alternatives>
      <tex-math><![CDATA[O(p^3)]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>O</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:msup><mml:mi>p</mml:mi><mml:mn>3</mml:mn></mml:msup><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow></mml:math></alternatives></inline-formula>
      operations.</p>
      <p specific-use="wrapper">
        <preformat>L &lt;- 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</preformat>
      </p>
    </list-item>
    <list-item>
      <label>66.</label>
      <p>When the matrix is symmetric, declare it. By default
      <monospace>eigen</monospace> 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.</p>
      <p specific-use="wrapper">
        <preformat>eigen(S)                                       ## classical
eigen(S, symmetric = TRUE)                     ## more efficient
eigen(S, symmetric = TRUE, only.values = TRUE) ## eigenvalues only</preformat>
      </p>
    </list-item>
    <list-item>
      <label>67.</label>
      <p>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
      <named-content content-type="sans-serif">Matrix</named-content>
      (Bates et al., 2026) stores only the non–zero elements, and the
      cost of multiplication and <monospace>solve</monospace> scales
      with the number of non–zeros. Sparsity is lost by operations that
      fill in the zeros, e.g. adding a scalar or centering.</p>
      <p specific-use="wrapper">
        <preformat>library(Matrix)
xs &lt;- Matrix(x, sparse = TRUE)
crossprod(xs)                    ## works as for a dense matrix
solve(xs, b)</preformat>
      </p>
    </list-item>
    <list-item>
      <label>68.</label>
      <p>Single precision. <italic>R</italic> stores real numbers in
      double precision (8 bytes). The package
      <named-content content-type="sans-serif">float</named-content>
      (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.</p>
      <p specific-use="wrapper">
        <preformat>library(float)
xf &lt;- fl(x)               ## half the memory of x
crossprod(xf)
dbl( crossprod(xf) )      ## back to double precision</preformat>
      </p>
    </list-item>
    <list-item>
      <label>69.</label>
      <p>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. <monospace>lm.fit</monospace> and
      <monospace>.lm.fit</monospace> accept a matrix of responses and
      fit all the regressions with a single QR decomposition of
      <monospace>x</monospace>. If the responses arrive one at a time,
      compute the QR decomposition once and reuse it.</p>
      <p specific-use="wrapper">
        <preformat>for (j in 1:q)  b[, j] &lt;- lm.fit(x, Y[, j])$coefficients  ## classical
b &lt;- lm.fit(x, Y)$coefficients                            ## efficient
q &lt;- qr(x)           ## decompose once
qr.coef(q, y1)       ## reuse for each response
qr.coef(q, y2)</preformat>
      </p>
    </list-item>
    <list-item>
      <label>70.</label>
      <p>Keep distances as a <monospace>dist</monospace> object. The
      function <monospace>dist</monospace> returns the lower triangle of
      the distance matrix as a vector of <inline-formula><alternatives>
      <tex-math><![CDATA[n(n-1)/2]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>n</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>n</mml:mi><mml:mo>−</mml:mo><mml:mn>1</mml:mn><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mi>/</mml:mi><mml:mn>2</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
      elements. Converting it to a full matrix more than doubles the
      memory, and many functions (<monospace>hclust</monospace>,
      <monospace>cmdscale</monospace>) accept the
      <monospace>dist</monospace> object directly. If the full matrix is
      required, <italic>Rfast</italic> computes it directly in
      <italic>C++</italic>.</p>
      <p specific-use="wrapper">
        <preformat>d &lt;- as.matrix( dist(x) )           ## classical, n x n matrix
d &lt;- dist(x)                        ## n(n-1)/2 vector, half the memory
d &lt;- Rfast::Dist(x)                 ## full matrix, much faster
d &lt;- Rfast::Dist(x, result = &quot;vector&quot;)  ## lower triangle only
d &lt;- Rfast::dista(x, y)             ## distances between rows of x and y</preformat>
      </p>
    </list-item>
    <list-item>
      <label>71.</label>
      <p>To sum many matrices of the same dimensions stored in a list
      <monospace>A</monospace>, use <monospace>Reduce</monospace>. This
      applies the operator cumulatively and allocates one result,
      instead of copying all the matrices into an array first.</p>
      <p specific-use="wrapper">
        <preformat>apply( simplify2array(A), 1:2, sum )  ## classical
Reduce(&quot;+&quot;, A)                        ## more efficient</preformat>
      </p>
    </list-item>
    <list-item>
      <label>72.</label>
      <p>The function <monospace>quantile</monospace> is surprisingly
      slow, because it sorts the whole vector and handles nine quantile
      definitions. If a single quantile is needed, use partial sorting.
      The <inline-formula><alternatives>
      <tex-math><![CDATA[k]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>k</mml:mi></mml:math></alternatives></inline-formula>–th
      smallest value is <monospace>sort(x, partial = k)[k]</monospace>,
      and the default (type 7) quantile of order
      <inline-formula><alternatives>
      <tex-math><![CDATA[\alpha]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>α</mml:mi></mml:math></alternatives></inline-formula>
      interpolates between two order statistics.</p>
      <p specific-use="wrapper">
        <preformat>quantile(x, alpha)                        ## classical
h &lt;- (n - 1) * alpha + 1
k &lt;- floor(h)
y &lt;- sort(x, partial = c(k, k + 1))
q &lt;- y[k] + (h - k) * (y[k + 1] - y[k])   ## more efficient</preformat>
      </p>
      <p>For the median, <monospace>median</monospace> already uses this
      trick, and <monospace>colMedians</monospace> of
      <italic>Rfast</italic> applies it column–wise.</p>
    </list-item>
  </list>
</sec>
<sec id="numerical-optimization">
  <title><named-content content-type="header-section-number">6</named-content>
  Numerical optimization</title>
  <list list-type="order">
    <list-item>
      <label>73.</label>
      <p>The command <monospace>nlm</monospace> is usually faster than
      <monospace>optim</monospace> for optimization purposes, but
      <monospace>optim</monospace> is more reliable and robust. In some
      cases <monospace>optim</monospace> with the argument
      <monospace>method = &quot;BFGS&quot;</monospace> can be faster,
      but these depend upon the function being minimized.</p>
    </list-item>
    <list-item>
      <label>74.</label>
      <p>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 <inline-formula><alternatives>
      <tex-math><![CDATA[\mathbb{R}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="double-struck">ℝ</mml:mi></mml:math></alternatives></inline-formula>,
      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 <inline-formula><alternatives>
      <tex-math><![CDATA[\delta]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>δ</mml:mi></mml:math></alternatives></inline-formula>–method
      (Casella &amp; Berger, 2002). The trick is to use a link function,
      similarly to generalised linear models.</p>
    </list-item>
    <list-item>
      <label>75.</label>
      <p>There are two ways to estimate the parameters of a
      distribution, the Dirichlet for example: either with the use of
      <monospace>nlm</monospace>, 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
      <monospace>nlm</monospace> with the E–M algorithm described by the
      same authors. Switching to E–M or Newton–Raphson, and not relying
      on <monospace>nlm</monospace>, 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.</p>
    </list-item>
    <list-item>
      <label>76.</label>
      <p>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
      <monospace>rbind</monospace>, <monospace>cbind</monospace> or
      <monospace>c()</monospace> to store the whole sequence. Instead,
      we store only two values, <monospace>vec.old</monospace> and
      <monospace>vec.new</monospace>. That is, we should not type</p>
      <p specific-use="wrapper">
        <preformat>u[i, ] &lt;- u[i - 1, ] + W %*% B  ## not efficient</preformat>
      </p>
      <p>but</p>
      <p specific-use="wrapper">
        <preformat>u.new &lt;- u.old + W %*% B        ## efficient</preformat>
      </p>
      <p>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.</p>
    </list-item>
  </list>
</sec>
<sec id="numerical-overflows">
  <title><named-content content-type="header-section-number">7</named-content>
  Numerical overflows</title>
  <p>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.</p>
  <list list-type="order">
    <list-item>
      <label>77.</label>
      <p>The fitted values of a logistic regression model make use of
      the inverse logit function <inline-formula><alternatives>
      <tex-math><![CDATA[\frac{e^x}{1+e^x}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mfrac><mml:msup><mml:mi>e</mml:mi><mml:mi>x</mml:mi></mml:msup><mml:mrow><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:msup><mml:mi>e</mml:mi><mml:mi>x</mml:mi></mml:msup></mml:mrow></mml:mfrac></mml:math></alternatives></inline-formula>.
      If <inline-formula><alternatives>
      <tex-math><![CDATA[x]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>x</mml:mi></mml:math></alternatives></inline-formula>
      is a very large number, both the numerator and the denominator
      overflow to <monospace>Inf</monospace> and the result is
      <monospace>NaN</monospace>. If, however, we write the formula in
      its equivalent form <inline-formula><alternatives>
      <tex-math><![CDATA[\frac{1}{1+e^{-x}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mfrac><mml:mn>1</mml:mn><mml:mrow><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:msup><mml:mi>e</mml:mi><mml:mrow><mml:mi>−</mml:mi><mml:mi>x</mml:mi></mml:mrow></mml:msup></mml:mrow></mml:mfrac></mml:math></alternatives></inline-formula>,
      the result is 1, as it should be.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- 1000
exp(x) / (1 + exp(x))   ## NaN
1 / (1 + exp(-x))       ## 1</preformat>
      </p>
    </list-item>
    <list-item>
      <label>78.</label>
      <p>The same is true for the Poisson regression, or other
      regressions that use the log link function. In those cases
      <inline-formula><alternatives>
      <tex-math><![CDATA[e^x]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mi>e</mml:mi><mml:mi>x</mml:mi></mml:msup></mml:math></alternatives></inline-formula>
      is used. It might be useful to consider using
      <inline-formula><alternatives>
      <tex-math><![CDATA[e^{-x}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mi>e</mml:mi><mml:mrow><mml:mi>−</mml:mi><mml:mi>x</mml:mi></mml:mrow></mml:msup></mml:math></alternatives></inline-formula>
      if there is a possibility of having very large values, or simply
      standardize the predictor variables.</p>
    </list-item>
    <list-item>
      <label>79.</label>
      <p>Kernel functions are of the form <inline-formula><alternatives>
      <tex-math><![CDATA[e^{\frac{f({\textbf{X}})}{h}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mi>e</mml:mi><mml:mfrac><mml:mrow><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mtext mathvariant="bold">𝐗</mml:mtext><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow><mml:mi>h</mml:mi></mml:mfrac></mml:msup></mml:math></alternatives></inline-formula>,
      where <inline-formula><alternatives>
      <tex-math><![CDATA[h]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>h</mml:mi></mml:math></alternatives></inline-formula>
      is a scalar and <inline-formula><alternatives>
      <tex-math><![CDATA[\mathbf{X}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi mathvariant="bold-italic">𝑿</mml:mi></mml:math></alternatives></inline-formula>
      is a matrix. In order to speed up the calculations one could
      pre–compute <inline-formula><alternatives>
      <tex-math><![CDATA[e^{f({\textbf{X}})}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mi>e</mml:mi><mml:mrow><mml:mi>f</mml:mi><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mtext mathvariant="bold">𝐗</mml:mtext><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow></mml:msup></mml:math></alternatives></inline-formula>
      and then raise the result to the power
      <inline-formula><alternatives>
      <tex-math><![CDATA[1/h]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>1</mml:mn><mml:mi>/</mml:mi><mml:mi>h</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
      for the different values of <inline-formula><alternatives>
      <tex-math><![CDATA[h]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>h</mml:mi></mml:math></alternatives></inline-formula>.
      This can easily result in overflow and <monospace>Inf</monospace>
      values and hence caution must be taken.</p>
    </list-item>
    <list-item>
      <label>80.</label>
      <p>The function <inline-formula><alternatives>
      <tex-math><![CDATA[\log{(1+e^x)}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mrow><mml:mi mathvariant="normal">log</mml:mi><mml:mo>&#8289;</mml:mo></mml:mrow><mml:mrow><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:msup><mml:mi>e</mml:mi><mml:mi>x</mml:mi></mml:msup><mml:mo stretchy="false" form="postfix">)</mml:mo></mml:mrow></mml:mrow></mml:math></alternatives></inline-formula>
      behaves like <inline-formula><alternatives>
      <tex-math><![CDATA[x]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>x</mml:mi></mml:math></alternatives></inline-formula>
      for large <inline-formula><alternatives>
      <tex-math><![CDATA[x]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>x</mml:mi></mml:math></alternatives></inline-formula>;
      in double precision the two become equal for
      <inline-formula><alternatives>
      <tex-math><![CDATA[x \gtrsim 37]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>x</mml:mi><mml:mo>≳</mml:mo><mml:mn>37</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>,
      and <inline-formula><alternatives>
      <tex-math><![CDATA[e^x]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mi>e</mml:mi><mml:mi>x</mml:mi></mml:msup></mml:math></alternatives></inline-formula>
      overflows for <inline-formula><alternatives>
      <tex-math><![CDATA[x > 709]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>x</mml:mi><mml:mo>&gt;</mml:mo><mml:mn>709</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>,
      so that even <monospace>log1p(exp(x))</monospace> returns
      <monospace>Inf</monospace>. The stable way to compute it is
      <inline-formula><alternatives>
      <tex-math><![CDATA[\max(x, 0) + \log{\left(1 + e^{-|x|}\right)}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mrow><mml:mi mathvariant="normal">max</mml:mi><mml:mo>&#8289;</mml:mo></mml:mrow><mml:mo stretchy="false" form="prefix">(</mml:mo><mml:mi>x</mml:mi><mml:mo>,</mml:mo><mml:mn>0</mml:mn><mml:mo stretchy="false" form="postfix">)</mml:mo><mml:mo>+</mml:mo><mml:mrow><mml:mi mathvariant="normal">log</mml:mi><mml:mo>&#8289;</mml:mo></mml:mrow><mml:mrow><mml:mo stretchy="true" form="prefix">(</mml:mo><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:msup><mml:mi>e</mml:mi><mml:mrow><mml:mi>−</mml:mi><mml:mo stretchy="false" form="prefix">|</mml:mo><mml:mi>x</mml:mi><mml:mo stretchy="false" form="prefix">|</mml:mo></mml:mrow></mml:msup><mml:mo stretchy="true" form="postfix">)</mml:mo></mml:mrow></mml:mrow></mml:math></alternatives></inline-formula>.</p>
      <p specific-use="wrapper">
        <preformat>log1p( exp(x) )                     ## Inf for x &gt; 709
pmax(x, 0) + log1p( exp(-abs(x)) )  ## never overflows</preformat>
      </p>
    </list-item>
    <list-item>
      <label>81.</label>
      <p>The product <inline-formula><alternatives>
      <tex-math><![CDATA[\prod_{i=1}^nx_i]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:msubsup><mml:mo>∏</mml:mo><mml:mrow><mml:mi>i</mml:mi><mml:mo>=</mml:mo><mml:mn>1</mml:mn></mml:mrow><mml:mi>n</mml:mi></mml:msubsup><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub></mml:mrow></mml:math></alternatives></inline-formula>,
      where <inline-formula><alternatives>
      <tex-math><![CDATA[0 < x_i \leq 1]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>0</mml:mn><mml:mo>&lt;</mml:mo><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub><mml:mo>≤</mml:mo><mml:mn>1</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>,
      underflows to <inline-formula><alternatives>
      <tex-math><![CDATA[0]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mn>0</mml:mn></mml:math></alternatives></inline-formula>
      very fast. In order to avoid this, we should compute
      <inline-formula><alternatives>
      <tex-math><![CDATA[e^{\sum_{i=1}^n\log{x_i}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mi>e</mml:mi><mml:mrow><mml:msubsup><mml:mo>∑</mml:mo><mml:mrow><mml:mi>i</mml:mi><mml:mo>=</mml:mo><mml:mn>1</mml:mn></mml:mrow><mml:mi>n</mml:mi></mml:msubsup><mml:mrow><mml:mi mathvariant="normal">log</mml:mi><mml:mo>&#8289;</mml:mo></mml:mrow><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub></mml:mrow></mml:msup></mml:math></alternatives></inline-formula>,
      or better, work with the logarithm of the product throughout.</p>
      <p specific-use="wrapper">
        <preformat>prod(x)             ## 0
exp( sum(log(x)) )  ## correct</preformat>
      </p>
    </list-item>
    <list-item>
      <label>82.</label>
      <p>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 <inline-formula><alternatives>
      <tex-math><![CDATA[1e-308]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>1</mml:mn><mml:mi>e</mml:mi><mml:mo>−</mml:mo><mml:mn>308</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
      (and subnormals to <inline-formula><alternatives>
      <tex-math><![CDATA[5e-324]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mn>5</mml:mn><mml:mi>e</mml:mi><mml:mo>−</mml:mo><mml:mn>324</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>),
      so <italic>R</italic> cannot sort them correctly since they are
      all considered equal. The logarithms of the p–values can be sorted
      correctly.</p>
      <p specific-use="wrapper">
        <preformat>pchisq(stat, dof, lower.tail = FALSE)                ## can be 0
pchisq(stat, dof, lower.tail = FALSE, log.p = TRUE)  ## sortable</preformat>
      </p>
    </list-item>
    <list-item>
      <label>83.</label>
      <p>The log–sum–exp trick. Quantities of the form
      <inline-formula><alternatives>
      <tex-math><![CDATA[\log{\sum_{i=1}^n e^{x_i}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mrow><mml:mi mathvariant="normal">log</mml:mi><mml:mo>&#8289;</mml:mo></mml:mrow><mml:mrow><mml:msubsup><mml:mo>∑</mml:mo><mml:mrow><mml:mi>i</mml:mi><mml:mo>=</mml:mo><mml:mn>1</mml:mn></mml:mrow><mml:mi>n</mml:mi></mml:msubsup><mml:msup><mml:mi>e</mml:mi><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub></mml:msup></mml:mrow></mml:mrow></mml:math></alternatives></inline-formula>
      appear in normalizing constants, mixture likelihoods, the softmax
      function and the E–step of the E–M algorithm. Computing them
      literally overflows when some <inline-formula><alternatives>
      <tex-math><![CDATA[x_i > 709]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub><mml:mo>&gt;</mml:mo><mml:mn>709</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>
      and underflows to <inline-formula><alternatives>
      <tex-math><![CDATA[-\infty]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>−</mml:mi><mml:mi>∞</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
      when all <inline-formula><alternatives>
      <tex-math><![CDATA[x_i < -745]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub><mml:mo>&lt;</mml:mo><mml:mi>−</mml:mi><mml:mn>745</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>.
      The stable formula is <inline-formula><alternatives>
      <tex-math><![CDATA[m + \log{\sum_{i=1}^n e^{x_i - m}}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>m</mml:mi><mml:mo>+</mml:mo><mml:mrow><mml:mi mathvariant="normal">log</mml:mi><mml:mo>&#8289;</mml:mo></mml:mrow><mml:mrow><mml:msubsup><mml:mo>∑</mml:mo><mml:mrow><mml:mi>i</mml:mi><mml:mo>=</mml:mo><mml:mn>1</mml:mn></mml:mrow><mml:mi>n</mml:mi></mml:msubsup><mml:msup><mml:mi>e</mml:mi><mml:mrow><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub><mml:mo>−</mml:mo><mml:mi>m</mml:mi></mml:mrow></mml:msup></mml:mrow></mml:mrow></mml:math></alternatives></inline-formula>
      with <inline-formula><alternatives>
      <tex-math><![CDATA[m = \max_i x_i]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>m</mml:mi><mml:mo>=</mml:mo><mml:msub><mml:mrow><mml:mi mathvariant="normal">max</mml:mi><mml:mo>&#8289;</mml:mo></mml:mrow><mml:mi>i</mml:mi></mml:msub><mml:msub><mml:mi>x</mml:mi><mml:mi>i</mml:mi></mml:msub></mml:mrow></mml:math></alternatives></inline-formula>,
      since then the largest exponent is <inline-formula><alternatives>
      <tex-math><![CDATA[e^0 = 1]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:msup><mml:mi>e</mml:mi><mml:mn>0</mml:mn></mml:msup><mml:mo>=</mml:mo><mml:mn>1</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>.</p>
      <p specific-use="wrapper">
        <preformat>log( sum( exp(x) ) )          ## overflows
m &lt;- max(x)
m + log( sum( exp(x - m) ) )  ## stable
matrixStats::logSumExp(x)     ## the same, and row/column versions</preformat>
      </p>
    </list-item>
    <list-item>
      <label>84.</label>
      <p>Work with log–densities. All the density functions of
      <italic>R</italic> accept <monospace>log = TRUE</monospace> and
      compute the logarithm directly, whereas
      <monospace>log(dnorm(...))</monospace> underflows to
      <inline-formula><alternatives>
      <tex-math><![CDATA[-\infty]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mi>−</mml:mi><mml:mi>∞</mml:mi></mml:mrow></mml:math></alternatives></inline-formula>
      in the tails. Similarly, <monospace>lgamma</monospace>,
      <monospace>lbeta</monospace>, <monospace>lchoose</monospace> and
      <monospace>lfactorial</monospace> should be used instead of the
      logarithm of <monospace>gamma</monospace>,
      <monospace>beta</monospace>, <monospace>choose</monospace> and
      <monospace>factorial</monospace>, which overflow. Exponentiate, if
      at all, only at the very end.</p>
      <p specific-use="wrapper">
        <preformat>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</preformat>
      </p>
    </list-item>
    <list-item>
      <label>85.</label>
      <p>Integer overflow. Integers in <italic>R</italic> are 32–bit, so
      the largest one is <monospace>.Machine$integer.max</monospace>
      <inline-formula><alternatives>
      <tex-math><![CDATA[= 2,147,483,647]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mrow><mml:mo>=</mml:mo><mml:mn>2</mml:mn><mml:mo>,</mml:mo><mml:mn>147</mml:mn><mml:mo>,</mml:mo><mml:mn>483</mml:mn><mml:mo>,</mml:mo><mml:mn>647</mml:mn></mml:mrow></mml:math></alternatives></inline-formula>.
      Arithmetic between integers that exceeds this returns
      <monospace>NA</monospace> with a warning. This typically arises
      when <monospace>n</monospace> comes from
      <monospace>length</monospace>, <monospace>dim</monospace> or
      <monospace>nrow</monospace>, which return integers. For exact
      arithmetic beyond <inline-formula><alternatives>
      <tex-math><![CDATA[2^{53}]]></tex-math>
      <mml:math display="inline" xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:msup><mml:mn>2</mml:mn><mml:mn>53</mml:mn></mml:msup></mml:math></alternatives></inline-formula>
      the package
      <named-content content-type="sans-serif">bit64</named-content>
      (Chirico &amp; Oehlschlägel, 2026) provides 64–bit integers.</p>
      <p specific-use="wrapper">
        <preformat>n &lt;- dim(x)[1]         ## an integer, say 50000
n * n                  ## NA with a warning
as.numeric(n) * n      ## 2.5e9</preformat>
      </p>
    </list-item>
  </list>
</sec>
<sec id="reading-largescale-datasets">
  <title><named-content content-type="header-section-number">8</named-content>
  Reading large–scale datasets</title>
  <list list-type="order">
    <list-item>
      <label>86.</label>
      <p>For reading large text files, <monospace>read.csv</monospace>
      and <monospace>read.table</monospace> are slow: they read the file
      line by line and guess the type of every column. The function
      <monospace>fread</monospace> of the package
      <named-content content-type="sans-serif">data.table</named-content>
      reads the file with multiple threads and is typically more than 10
      times faster; <monospace>read_csv</monospace> of
      <named-content content-type="sans-serif">readr</named-content>
      (Wickham et al., 2026) is a second option.</p>
      <p specific-use="wrapper">
        <preformat>x &lt;- read.csv(&quot;data.csv&quot;)             ## classical
x &lt;- data.table::fread(&quot;data.csv&quot;)    ## much faster</preformat>
      </p>
    </list-item>
  </list>
</sec>
<sec id="parallel-computing-in-r">
  <title><named-content content-type="header-section-number">9</named-content>
  Parallel computing in <italic>R</italic></title>
  <p>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.</p>
  <p>The idea is to use a library that allows parallel computing. We
  make use of the built–in
  <named-content content-type="sans-serif">parallel</named-content>
  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
  (<monospace>zip.mle</monospace>) is available in the package
  <named-content content-type="sans-serif">Rfast</named-content>
  (Papadakis et al., 2025).</p>
  <preformat>n &lt;- dim(x)[2]
res &lt;- matrix(nrow = n, ncol = 4)
for ( i in 1:n )  res[i, ] &lt;- unlist( Rfast::zip.mle(x[, i], 1e-6) )
colnames(res) &lt;- c('iters', 'loglik', 'lambda', 'pi')</preformat>
  <p>Using the
  <named-content content-type="sans-serif">parallel</named-content>
  package the above code translates into the following.</p>
  <preformat>cl &lt;- makeCluster(ncores)  ## ncores is the number of cores to use
clusterExport(cl, &quot;x&quot;)
clusterEvalQ(cl, library(Rfast))
res &lt;- parSapply(cl, 1:n, function(i) unlist(Rfast::zip.mle(x[, i], 1e-6)))
stopCluster(cl)
res &lt;- t(res)
colnames(res) &lt;- c('iters', 'loglik', 'lambda', 'pi')</preformat>
  <list list-type="order">
    <list-item>
      <label>87.</label>
      <p>On Linux and macOS, <monospace>mclapply</monospace> of the
      built–in package
      <named-content content-type="sans-serif">parallel</named-content>
      package is often simpler and faster than a socket cluster: it
      forks the current <italic>R</italic> process, so the workers see
      all its objects without any copying or exporting, and there is no
      cluster to set up or stop.</p>
      <p specific-use="wrapper">
        <preformat>res &lt;- parallel::mclapply(1:B, f, mc.cores = nc)  ## Linux / macOS</preformat>
      </p>
      <p>The previous example for instance would be</p>
      <p specific-use="wrapper">
        <preformat>res_list &lt;- mclapply(1:n, function(i) unlist(Rfast::zip.mle(x[, i], 1e-6)), 
mc.cores = ncores)
res &lt;- do.call(rbind, res_list)
colnames(res) &lt;- c('iters', 'loglik', 'lambda', 'pi')  </preformat>
      </p>
    </list-item>
  </list>
</sec>
<sec id="efficiently-written-functions-in-r-packages">
  <title><named-content content-type="header-section-number">10</named-content>
  Efficiently written functions in <italic>R</italic> packages</title>
  <p>Multinomial regression is offered in the package
  <named-content content-type="sans-serif">VGAM</named-content> (Yee,
  2010), but also in the package
  <named-content content-type="sans-serif">nnet</named-content>
  (Venables &amp; Ripley, 2002). The implementation in the second
  package is much faster. The same is true for ordinal logistic
  regression in
  <named-content content-type="sans-serif">VGAM</named-content> and in
  <named-content content-type="sans-serif">ordinal</named-content>
  (Christensen, 2015); the latter is much faster. Also, the package
  <italic>fields</italic> (Nychka et al., 2015) has a function called
  <monospace>rdist</monospace> which is faster than the built–in
  <monospace>dist</monospace>. A fast implementation of the distance
  correlation is available in the package
  <named-content content-type="sans-serif">dcov</named-content>
  (Weiqiang, 2020), and more memory– and computationally–efficient
  energy–related functions can be found in the package
  <named-content content-type="sans-serif">estats</named-content><xref ref-type="fn" rid="fn4">4</xref>
  (Tsagris &amp; 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.</p>
  <p>Regression models, distance matrix computations, statistical tests,
  utility functions and many more can also be found in the packages
  <named-content content-type="sans-serif">Rfast</named-content>
  (Papadakis et al., 2025) and
  <named-content content-type="sans-serif">Rfast2</named-content>
  (Papadakis et al., 2026). These two packages contain many fast or
  really fast functions, either written in <italic>C++</italic> or
  written in <italic>R</italic> exploiting fast built–in functions. The
  packages
  <named-content content-type="sans-serif">matrixStats</named-content>
  (Bengtsson, 2025) and
  <named-content content-type="sans-serif">collapse</named-content>
  (Krantz, 2026) offer similar collections of row– and column–wise
  functions written in <italic>C</italic> or <italic>C++</italic>, and
  they complement each other.</p>
</sec>
<sec id="more-advanced-programming-tips">
  <title><named-content content-type="header-section-number">11</named-content>
  More advanced programming tips</title>
  <p>Some programming languages offer advanced features. We mention some
  of those that <italic>R</italic> supports, along with their strengths
  and benefits.</p>
  <list list-type="order">
    <list-item>
      <label>88.</label>
      <p>Auto–printing our own class in our own style. In
      <italic>R</italic> we can print a variable using the functions
      <monospace>print</monospace> and <monospace>cat</monospace>, or by
      just typing the variable’s name and pressing enter. But what if we
      do not like the way <italic>R</italic> prints it? That is the
      point of auto–printing. <italic>R</italic> supports a general way
      to print our own class through its default function
      <monospace>print</monospace>. The method is very simple, with one
      requirement: we must change the class.</p>
      <p specific-use="wrapper">
        <preformat>print.new_class_name &lt;- function(x, ...) {
  cat(&quot;auto-printing my variable with class 'new_class_name' 
  and value: &quot;, x)
}</preformat>
      </p>
      <p>Example:</p>
      <list list-type="alpha-lower">
        <list-item>
          <label>(a)</label>
          <p>Create a variable: <monospace>x &lt;- 0</monospace></p>
        </list-item>
        <list-item>
          <label>(b)</label>
          <p>Change its class:
          <monospace>class(x) &lt;- &quot;anything&quot;</monospace></p>
        </list-item>
        <list-item>
          <label>(c)</label>
          <p>Create the function to print the variable:</p>
          <p specific-use="wrapper">
            <preformat> print.anything &lt;- function(x, ...) {
   cat(&quot;Auto-printing variable of class anything: &quot;, x)
 }</preformat>
          </p>
        </list-item>
        <list-item>
          <label>(d)</label>
          <p>Type: <monospace>print(x)</monospace>, or simply
          <monospace>x</monospace>.</p>
        </list-item>
        <list-item>
          <label>(e)</label>
          <p>That’s it.</p>
        </list-item>
      </list>
    </list-item>
    <list-item>
      <label>89.</label>
      <p>Using <monospace>if-else</monospace> in one line. Another
      feature of <italic>C++</italic> is the ternary operator (which
      cannot be overloaded). It is an <monospace>if-else</monospace>
      statement with a different syntax and one more capability: it
      returns the value of the selected branch, i.e. it is an
      <monospace>if-else</monospace> with assignment. <italic>R</italic>
      supports the same thing with its default
      <monospace>if-else</monospace> syntax, which can reduce the length
      of the code.
      Example:</p>
      <p specific-use="wrapper">
        <preformat>  if ( is_true ) {
    x &lt;- 1
  } else {
    x &lt;- 2
  }</preformat>
      </p>
      <p>The above example is very simple but needs 5 lines. Let us
      reduce it:</p>
      <p specific-use="wrapper">
        <preformat>  x &lt;- if (is_true)  1  else  2</preformat>
      </p>
      <p>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 <monospace>x</monospace>. For more than one
      command use curly brackets. This works because
      <monospace>if-else</monospace> in <italic>R</italic> is like a
      function that always returns its last evaluated expression,
      without the <monospace>return</monospace> keyword.
      <italic>Note:</italic> the same holds for
      <monospace>if-else-if</monospace>. This is a matter of style;
      there is no speed difference, since it is the same
      <monospace>if</monospace> construct.</p>
    </list-item>
    <list-item>
      <label>90.</label>
      <p>Iterating over a vector. If we want to iterate over a vector
      and use its elements, we can write:</p>
      <p specific-use="wrapper">
        <preformat>  x &lt;- rnorm(10)
  for ( i in seq_along(x) ) {
    cat(x[i])
  }</preformat>
      </p>
      <p>This is the classic way. Another way is:</p>
      <p specific-use="wrapper">
        <preformat>  x &lt;- rnorm(10)
  for ( i in x ) {
    cat(i)
  }</preformat>
      </p>
      <p>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. <monospace>length(x)</monospace> operations in total. The
      gain is small though.</p>
    </list-item>
    <list-item>
      <label>91.</label>
      <p>Use &quot;<monospace>[[</monospace>&quot; instead of
      &quot;<monospace>$</monospace>&quot; for programmatic access to
      lists and data frames. The &quot;<monospace>$</monospace>&quot;
      operator performs partial matching on the name, which is a source
      of bugs in functions, and on data frames it dispatches to a
      method. &quot;<monospace>[[</monospace>&quot; matches exactly,
      takes the name as a variable, and is faster inside loops. The
      internal <monospace>.subset2</monospace> does the same without any
      dispatch.</p>
      <p specific-use="wrapper">
        <preformat>x$val                 ## returns x$value if &quot;val&quot; is a unique prefix
x[[&quot;value&quot;]]          ## exact, and the name can be a variable
.subset2(x, &quot;value&quot;)  ## no dispatch at all</preformat>
      </p>
    </list-item>
  </list>
</sec>
<sec id="conclusions">
  <title><named-content content-type="header-section-number">12</named-content>
  Conclusions</title>
  <p>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.</p>
</sec>
<sec id="acknowledgements">
  <title>Acknowledgements</title>
  <p>We would like to thank Stefanos Fafalios, Christina Chatzipantsiou,
  Marco Maier, Panagiotis Tzirakis, Giorgos Athineou, Kleio Lakiotaki,
  Kurt Hornik, Uwe Ligges and the <italic>R</italic> Core team.</p>
</sec>
<sec id="conflicts-of-interests">
  <title>Conflicts of Interests</title>
  <p>M. Tsagris and M. Papadakis are the maintainers of the
  <italic>R</italic> packages
  <named-content content-type="sans-serif">Rfast</named-content>,
  <named-content content-type="sans-serif">Rfast2</named-content> and
  <named-content content-type="sans-serif">estats</named-content>, which
  are recommended in this paper. The authors declare no other competing
  interests.</p>
</sec>
<sec sec-type="data-availability">
<title>Data and code availability</title>
<p>The code and data are in the reproducibility package published with this article (.zip). Running `cd code &amp;&amp; Rscript R_code.R` in the unpacked package regenerates the reported results. The journal ran this command and the reported values matched.</p>
</sec>
</body>
<back><ref-list><ref id="ref1"><mixed-citation>Barrett, T., Dowle, M., Srinivasan, A., Gorecki, J., Chirico, M., Hocking, T., Schwendinger, B., &amp; Krylov, I. (2026). data.table: Extension of ’data.frame’ [R package version 1.18.6.1]. https://doi.org/10.32614/CRAN.package.data.table</mixed-citation></ref><ref id="ref2"><mixed-citation>Bates, D., Maechler, M., &amp; Jagan, M. (2026). Matrix: Sparse and Dense Matrix Classes and Methods [R package version 1.7-5]. https://doi.org/10.32614/CRAN.package.Matrix</mixed-citation></ref><ref id="ref3"><mixed-citation>Bengtsson, H. (2025). matrixStats: Functions that Apply to Rows and Columns of Matrices (and to Vectors) [R package version 1.5.0]. https://doi.org/10.32614/CRAN.package.matrixStats</mixed-citation></ref><ref id="ref4"><mixed-citation>Burns, P. (2011). The R Inferno. https://www.burns-stat.com/pages/Tutor/R_inferno.pdf</mixed-citation></ref><ref id="ref5"><mixed-citation>Casella, G., &amp; Berger, R. L. (2002). Statistical Inference. Duxbury Pacific Grove, CA.</mixed-citation></ref><ref id="ref6"><mixed-citation>Chatzipantsiou, C., Dimitriadis, M., Papadakis, M., &amp; Tsagris, M. (2019). Extremely efficient permutation and bootstrap hypothesis tests using R. Journal of Modern Applied Statistical Methods, 18(2), eP2898. https://doi.org/10.22237/jmasm/1604189940</mixed-citation></ref><ref id="ref7"><mixed-citation>Chirico, M., &amp; Oehlschlägel, J. (2026). bit64: A S3 Class for Vectors of 64bit Integers [R package version 4.8.6]. https://doi.org/10.32614/CRAN.package.bit64</mixed-citation></ref><ref id="ref8"><mixed-citation>Christensen, R. H. B. (2015). ordinal—Regression Models for Ordinal Data [R package version 2015.6-28]. http://www.cran.r-project.org/package=ordinal/</mixed-citation></ref><ref id="ref9"><mixed-citation>Gillespie, C., &amp; Lovelace, R. (2016). Efficient R programming: a practical guide to smarter programming. O’Reilly Media, Inc.</mixed-citation></ref><ref id="ref10"><mixed-citation>Hester, J., &amp; Vaughan, D. (2025). bench: High Precision Timing of R Expressions [R package version 1.1.4]. https://doi.org/10.32614/CRAN.package.bench</mixed-citation></ref><ref id="ref11"><element-citation publication-type="journal"><person-group person-group-type="author"><name><surname>Krantz</surname><given-names>Sebastian</given-names></name></person-group><article-title>collapse
                    : Advanced and Fast Statistical Computing and Data Transformation in
                    &lt;i&gt;R&lt;/i&gt;</article-title><source>Journal of Statistical Software</source><year>2026</year><volume>116</volume><issue>1</issue><publisher-name>Foundation for Open Access Statistic</publisher-name><pub-id pub-id-type="doi">10.18637/jss.v116.i01</pub-id></element-citation></ref><ref id="ref12"><mixed-citation>Mersmann, O. (2015). microbenchmark: Accurate Timing Functions [R package version 1.4-2.1]. http://CRAN.R-project.org/package=microbenchmark</mixed-citation></ref><ref id="ref13"><mixed-citation>Nychka, D., Furrer, R., &amp; Sain, S. (2015). fields: Tools for Spatial Data [R package version 8.2-1]. http://CRAN.R-project.org/package=fields</mixed-citation></ref><ref id="ref14"><mixed-citation>Papadakis, M., Tsagris, M., Dimitriadis, M., Fafalios, S., Fasiolo, M., Jacob, M., Borboudakis, G., Burkardt, J., &amp; Zou, C. (2025). Rfast: A Collection of Efficient and Extremely Fast R Functions [R package version 2.1.5.2]. http://CRAN.R-project.org/package=Rfast</mixed-citation></ref><ref id="ref15"><mixed-citation>Papadakis, M., Tsagris, M., Fafalios, S., Dimitriadis, M., Lasithiotakis, M., &amp; Kontemeniotis, N. (2026). Rfast2: A Collection of Efficient and Extremely Fast R Functions II [R package version 0.1.5.6]. http://CRAN.R-project.org/package=Rfast2</mixed-citation></ref><ref id="ref16"><element-citation publication-type="journal"><person-group person-group-type="author"><name><surname>Presnell</surname><given-names>Brett</given-names></name><name><surname>Morrison</surname><given-names>Scott P.</given-names></name><name><surname>Littell</surname><given-names>Ramon C.</given-names></name></person-group><article-title>Projected Multivariate Linear Models for Directional Data</article-title><source>Journal of the American Statistical Association</source><year>1998</year><volume>93</volume><issue>443</issue><fpage>1068</fpage><lpage>1077</lpage><publisher-name>Informa UK Limited</publisher-name><pub-id pub-id-type="doi">10.1080/01621459.1998.10473768</pub-id></element-citation></ref><ref id="ref17"><mixed-citation>Schmidt, D. (2025). float: 32-Bit Floats [R package version 0.3-3]. https://doi.org/10.32614/CRAN.package.float</mixed-citation></ref><ref id="ref18"><mixed-citation>Strang, G. (2023). Introduction to Linear Algebra (6th edition). Wellesley-Cambridge Press, USA.</mixed-citation></ref><ref id="ref19"><mixed-citation>Tsagris, M. (2017). Conditional Independence test for categorical data using Poisson log-linear model. Journal of Data Science, 15(2), 345–354. https://arxiv.org/pdf/1706.02046.pdf</mixed-citation></ref><ref id="ref20"><element-citation publication-type="journal"><person-group person-group-type="author"><name><surname>Tsagris</surname><given-names>Michail</given-names></name><name><surname>Papadakis</surname><given-names>Manos</given-names></name></person-group><article-title>Taking R to its limits: 70+ tips</article-title><year>2018</year><publisher-name>PeerJ</publisher-name><pub-id pub-id-type="doi">10.7287/peerj.preprints.26605v1</pub-id></element-citation></ref><ref id="ref21"><mixed-citation>Tsagris, M., &amp; Papadakis, M. (2026a). estats: Fast and Light-Weight Energy Statistics [R package version 1.1].</mixed-citation></ref><ref id="ref22"><element-citation publication-type="journal"><person-group person-group-type="author"><name><surname>Tsagris</surname><given-names>Michail</given-names></name><name><surname>Papadakis</surname><given-names>Manos</given-names></name></person-group><article-title>Fast and light-weight energy statistics using the
                    &lt;i&gt;R&lt;/i&gt;
                    package estats</article-title><source>Journal of Statistical Computation and Simulation</source><year>2026</year><volume>96</volume><issue>7</issue><fpage>1589</fpage><lpage>1605</lpage><publisher-name>Informa UK Limited</publisher-name><pub-id pub-id-type="doi">10.1080/00949655.2025.2601701</pub-id></element-citation></ref><ref id="ref23"><element-citation publication-type="book"><person-group person-group-type="author"><name><surname>Venables</surname><given-names>W. N.</given-names></name><name><surname>Ripley</surname><given-names>B. D.</given-names></name></person-group><article-title>Modern Applied Statistics with S</article-title><source>Statistics and Computing</source><year>2002</year><publisher-name>Springer New York</publisher-name><pub-id pub-id-type="doi">10.1007/978-0-387-21706-2</pub-id></element-citation></ref><ref id="ref24"><element-citation publication-type="data"><person-group person-group-type="author"><string-name>Hang Weiqiang &lt;e0010758@u.nus.edu&gt;</string-name></person-group><article-title>dcov: A Fast Implementation of Distance Covariance</article-title><source>CRAN: Contributed Packages</source><year>2020</year><publisher-name>The R Foundation</publisher-name><pub-id pub-id-type="doi">10.32614/CRAN.package.dcov</pub-id></element-citation></ref><ref id="ref25"><mixed-citation>Wickham, H. (2015). Advanced R. CRC Press.</mixed-citation></ref><ref id="ref26"><mixed-citation>Wickham, H., Hester, J., &amp; Bryan, J. (2026). readr: Read Rectangular Text Data [R package version 2.2.0]. https://doi.org/10.32614/CRAN.package.readr</mixed-citation></ref><ref id="ref27"><element-citation publication-type="journal"><person-group person-group-type="author"><name><surname>Yee</surname><given-names>Thomas W.</given-names></name></person-group><article-title>The
                    VGAM
                    Package for Categorical Data Analysis</article-title><source>Journal of Statistical Software</source><year>2010</year><volume>32</volume><issue>10</issue><publisher-name>Foundation for Open Access Statistic</publisher-name><pub-id pub-id-type="doi">10.18637/jss.v032.i10</pub-id></element-citation></ref></ref-list>
<ref-list>
  <title>References</title>
  <ref id="ref-datatable2026">
    <mixed-citation>Barrett, T., Dowle, M., Srinivasan, A., Gorecki, J.,
    Chirico, M., Hocking, T., Schwendinger, B., &amp; Krylov, I. (2026).
    <italic><named-content content-type="nocase">data.table: Extension
    of ’data.frame’</named-content></italic> [R package version
    1.18.6.1].
    <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.32614/CRAN.package.data.table">https://doi.org/10.32614/CRAN.package.data.table</ext-link></mixed-citation>
  </ref>
  <ref id="ref-matrix2026">
    <mixed-citation>Bates, D., Maechler, M., &amp; Jagan, M. (2026).
    <italic><named-content content-type="nocase">Matrix: Sparse and
    Dense Matrix Classes and Methods</named-content></italic> [R package
    version 1.7-5].
    <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.32614/CRAN.package.Matrix">https://doi.org/10.32614/CRAN.package.Matrix</ext-link></mixed-citation>
  </ref>
  <ref id="ref-matrixstats2025">
    <mixed-citation>Bengtsson, H. (2025).
    <italic><named-content content-type="nocase">matrixStats: Functions
    that Apply to Rows and Columns of Matrices (and to
    Vectors)</named-content></italic> [R package version 1.5.0].
    <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.32614/CRAN.package.matrixStats">https://doi.org/10.32614/CRAN.package.matrixStats</ext-link></mixed-citation>
  </ref>
  <ref id="ref-burns2011">
    <mixed-citation>Burns, P. (2011). <italic>The R Inferno</italic>.
    <ext-link ext-link-type="uri" xlink:href="https://www.burns-stat.com/pages/Tutor/R_inferno.pdf">https://www.burns-stat.com/pages/Tutor/R_inferno.pdf</ext-link></mixed-citation>
  </ref>
  <ref id="ref-casella2002">
    <mixed-citation>Casella, G., &amp; Berger, R. L. (2002).
    <italic>Statistical Inference</italic>. Duxbury Pacific Grove,
    CA.</mixed-citation>
  </ref>
  <ref id="ref-chatzipantsiou2019">
    <mixed-citation>Chatzipantsiou, C., Dimitriadis, M., Papadakis, M.,
    &amp; Tsagris, M. (2019).
    <named-content content-type="nocase">Extremely efficient permutation
    and bootstrap hypothesis tests using R</named-content>.
    <italic>Journal of Modern Applied Statistical Methods</italic>,
    <italic>18</italic>(2), eP2898.
    <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.22237/jmasm/1604189940">https://doi.org/10.22237/jmasm/1604189940</ext-link></mixed-citation>
  </ref>
  <ref id="ref-bit642026">
    <mixed-citation>Chirico, M., &amp; Oehlschlägel, J. (2026).
    <italic><named-content content-type="nocase">bit64: A S3 Class for
    Vectors of 64bit Integers</named-content></italic> [R package
    version 4.8.6].
    <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.32614/CRAN.package.bit64">https://doi.org/10.32614/CRAN.package.bit64</ext-link></mixed-citation>
  </ref>
  <ref id="ref-ordinal2015">
    <mixed-citation>Christensen, R. H. B. (2015).
    <italic><named-content content-type="nocase">ordinal—Regression
    Models for Ordinal Data</named-content></italic> [R package version
    2015.6-28].
    <ext-link ext-link-type="uri" xlink:href="http://www.cran.r-project.org/package=ordinal/">http://www.cran.r-project.org/package=ordinal/</ext-link></mixed-citation>
  </ref>
  <ref id="ref-gillespie2016">
    <mixed-citation>Gillespie, C., &amp; Lovelace, R. (2016).
    <italic><named-content content-type="nocase">Efficient R
    programming: a practical guide to smarter
    programming</named-content></italic>. O’Reilly Media,
    Inc.</mixed-citation>
  </ref>
  <ref id="ref-bench2025">
    <mixed-citation>Hester, J., &amp; Vaughan, D. (2025).
    <italic><named-content content-type="nocase">bench: High Precision
    Timing of R Expressions</named-content></italic> [R package version
    1.1.4].
    <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.32614/CRAN.package.bench">https://doi.org/10.32614/CRAN.package.bench</ext-link></mixed-citation>
  </ref>
  <ref id="ref-collapse2026">
    <mixed-citation>Krantz, S. (2026).
    <named-content content-type="nocase">collapse</named-content>:
    Advanced and fast statistical computing and data transformation in
    R. <italic>Journal of Statistical Software</italic>,
    <italic>116</italic>(1), 1–38.</mixed-citation>
  </ref>
  <ref id="ref-microbenchmark2015">
    <mixed-citation>Mersmann, O. (2015).
    <italic><named-content content-type="nocase">microbenchmark:
    Accurate Timing Functions</named-content></italic> [R package
    version 1.4-2.1].
    <ext-link ext-link-type="uri" xlink:href="http://CRAN.R-project.org/package=microbenchmark">http://CRAN.R-project.org/package=microbenchmark</ext-link></mixed-citation>
  </ref>
  <ref id="ref-fields2015">
    <mixed-citation>Nychka, D., Furrer, R., &amp; Sain, S. (2015).
    <italic><named-content content-type="nocase">fields: Tools for
    Spatial Data</named-content></italic> [R package version 8.2-1].
    <ext-link ext-link-type="uri" xlink:href="http://CRAN.R-project.org/package=fields">http://CRAN.R-project.org/package=fields</ext-link></mixed-citation>
  </ref>
  <ref id="ref-rfast2025">
    <mixed-citation>Papadakis, M., Tsagris, M., Dimitriadis, M.,
    Fafalios, S., Fasiolo, M., Jacob, M., Borboudakis, G., Burkardt, J.,
    &amp; Zou, C. (2025).
    <italic><named-content content-type="nocase">Rfast: A Collection of
    Efficient and Extremely Fast R Functions</named-content></italic> [R
    package version 2.1.5.2].
    <ext-link ext-link-type="uri" xlink:href="http://CRAN.R-project.org/package=Rfast">http://CRAN.R-project.org/package=Rfast</ext-link></mixed-citation>
  </ref>
  <ref id="ref-rfast22026">
    <mixed-citation>Papadakis, M., Tsagris, M., Fafalios, S.,
    Dimitriadis, M., Lasithiotakis, M., &amp; Kontemeniotis, N. (2026).
    <italic><named-content content-type="nocase">Rfast2: A Collection of
    Efficient and Extremely Fast R Functions II</named-content></italic>
    [R package version 0.1.5.6].
    <ext-link ext-link-type="uri" xlink:href="http://CRAN.R-project.org/package=Rfast2">http://CRAN.R-project.org/package=Rfast2</ext-link></mixed-citation>
  </ref>
  <ref id="ref-presnell1998">
    <mixed-citation>Presnell, B., Morrison, S. P., &amp; Littell, R. C.
    (1998). Projected multivariate linear models for directional data.
    <italic>Journal of the American Statistical Association</italic>,
    <italic>93</italic>(443), 1068–1077.
    <ext-link ext-link-type="uri" xlink:href="http://www.jstor.org/stable/pdf/2669850.pdf">http://www.jstor.org/stable/pdf/2669850.pdf</ext-link></mixed-citation>
  </ref>
  <ref id="ref-float20252026">
    <mixed-citation>Schmidt, D. (2025).
    <italic><named-content content-type="nocase">float: 32-Bit
    Floats</named-content></italic> [R package version 0.3-3].
    <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.32614/CRAN.package.float">https://doi.org/10.32614/CRAN.package.float</ext-link></mixed-citation>
  </ref>
  <ref id="ref-strang2023">
    <mixed-citation>Strang, G. (2023).
    <italic><named-content content-type="nocase">Introduction to Linear
    Algebra (6th edition)</named-content></italic>. Wellesley-Cambridge
    Press, USA.</mixed-citation>
  </ref>
  <ref id="ref-tsagris2017">
    <mixed-citation>Tsagris, M. (2017).
    <named-content content-type="nocase">Conditional Independence test
    for categorical data using Poisson log-linear model</named-content>.
    <italic>Journal of Data Science</italic>, <italic>15</italic>(2),
    345–354.
    <ext-link ext-link-type="uri" xlink:href="https://arxiv.org/pdf/1706.02046.pdf">https://arxiv.org/pdf/1706.02046.pdf</ext-link></mixed-citation>
  </ref>
  <ref id="ref-tsagris2018">
    <mixed-citation>Tsagris, M., &amp; Papadakis, M. (2018). Taking r to
    its limits: 70+ tips. <italic>PeerJ Preprints</italic>,
    <italic>6</italic>, e26605v1.</mixed-citation>
  </ref>
  <ref id="ref-estats2026">
    <mixed-citation>Tsagris, M., &amp; Papadakis, M. (2026a).
    <italic><named-content content-type="nocase">estats: Fast and
    Light-Weight Energy Statistics</named-content></italic> [R package
    version 1.1].</mixed-citation>
  </ref>
  <ref id="ref-tsagris2026">
    <mixed-citation>Tsagris, M., &amp; Papadakis, M. (2026b).
    <named-content content-type="nocase">Fast and light-weight energy
    statistics using the R package estats</named-content>.
    <italic>Journal of Statistical Computation and Simulation</italic>,
    <italic>96</italic>(7), 1589–1605.</mixed-citation>
  </ref>
  <ref id="ref-nnet">
    <mixed-citation>Venables, W. N., &amp; Ripley, B. D. (2002).
    <italic><named-content content-type="nocase">Modern Applied
    Statistics with S</named-content></italic> (Fourth). Springer.
    <ext-link ext-link-type="uri" xlink:href="http://www.stats.ox.ac.uk/pub/MASS4">http://www.stats.ox.ac.uk/pub/MASS4</ext-link></mixed-citation>
  </ref>
  <ref id="ref-dcov2020">
    <mixed-citation>Weiqiang, H. (2020).
    <italic><named-content content-type="nocase">dcov: A Fast
    Implementation of Distance Covariance</named-content></italic> [R
    package version 0.1.1].
    <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.32614/CRAN.package.dcov">https://doi.org/10.32614/CRAN.package.dcov</ext-link></mixed-citation>
  </ref>
  <ref id="ref-wickham2015">
    <mixed-citation>Wickham, H. (2015). <italic>Advanced R</italic>. CRC
    Press.</mixed-citation>
  </ref>
  <ref id="ref-readr2026">
    <mixed-citation>Wickham, H., Hester, J., &amp; Bryan, J. (2026).
    <italic><named-content content-type="nocase">readr: Read Rectangular
    Text Data</named-content></italic> [R package version 2.2.0].
    <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.32614/CRAN.package.readr">https://doi.org/10.32614/CRAN.package.readr</ext-link></mixed-citation>
  </ref>
  <ref id="ref-VGAM">
    <mixed-citation>Yee, T. W. (2010).
    <named-content content-type="nocase">The VGAM Package for
    Categorical Data Analysis</named-content>. <italic>Journal of
    Statistical Software</italic>, <italic>32</italic>(10), 1–34.
    <ext-link ext-link-type="uri" xlink:href="http://www.jstatsoft.org/v32/i10/">http://www.jstatsoft.org/v32/i10/</ext-link></mixed-citation>
  </ref>
</ref-list>
<fn-group>
  <fn id="fn1">
    <label>1</label><p>Note, however, that this is not always the
    case.</p>
  </fn>
  <fn id="fn2">
    <label>2</label><p>This was observed in our Windows operating
    laptop, and hence speed–up factors may vary across machines.</p>
  </fn>
  <fn id="fn3">
    <label>3</label><p>Note however, that
    <monospace>princomp</monospace> works from the covariance matrix and
    its eigendecomposition, which loses precision relative to the SVD of
    the centered data that <monospace>prcomp</monospace> uses, and the
    difference shows up on ill–conditioned or nearly collinear data that
    applied users might meet.</p>
  </fn>
  <fn id="fn4">
    <label>4</label><p>See (Tsagris &amp; Papadakis, 2026b) for the
    mathematical and computational tricks.</p>
  </fn>
</fn-group>
</back>
<sub-article id="pr-r1-letter" article-type="editor-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r1.letter</article-id>
<title-group>
<article-title>Decision letter, round 1</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<contrib-id contrib-id-type="orcid">https://orcid.org/0000-0002-8638-5276</contrib-id>
<string-name>Matthias Templ</string-name>
<role specific-use="editor">Editor</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="editor-decision-sent">
<event-desc>Editor decision sent</event-desc>
<date iso-8601-date="2026-10-02"><day>02</day><month>10</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>0</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>major-revision</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><bold>Major revision.</bold> Confirmed and signed by Matthias Templ on 2026-10-02.</p>
<p>Thank you for your submission to JRepStat. We are inviting a major revision. The reviewers’ points follow, grouped by weight.</p>
<p>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.</p>
<p>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.</p>
<p><sc>required</sc> (the decision rests on these):</p>
<list list-type="bullet">
  <list-item>
    <p>[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 <monospace>[[</monospace> versus <monospace>$</monospace> 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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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).</p>
  </list-item>
  <list-item>
    <p>[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”.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 3] Tip 17 option a3 divides <monospace>rowsum(x, ina, reorder = FALSE)</monospace> by <monospace>as.vector(table(ina))</monospace>, 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.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 3] Add data.table coverage beyond <monospace>fread</monospace>: keyed joins, grouped aggregation with <monospace>[, by = ]</monospace>, and update by reference, cross-referenced from tips 12 and 17.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 3] A short note on when to leave base R for Rcpp or RcppArmadillo yourself, not only via a wrapper package.</p>
  </list-item>
</list>
<p><sc>recommended</sc>:</p>
<list list-type="bullet">
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[methods-soundness] Tip 64 says at most n eigenvalues of the correlation matrix are non-zero when n &lt; 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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[writing-quality] Tip 80 contains a spelling error, “afraind”, that reads as an author typo rather than an extraction artefact. Please correct to “afraid”.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 2] Add collapse (fmean, fsum, fvar) to the grouped-operation tips (17, 38).</p>
  </list-item>
  <list-item>
    <p>[Reviewer 3] Note the numerical-stability cost of <monospace>princomp</monospace> over <monospace>prcomp</monospace> in tip 46, consistent with the paper’s own stability section.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 3] Add a note on reproducible parallel RNG (<monospace>clusterSetRNGStream</monospace>, <monospace>mc.set.seed</monospace>) in Section 9, given the simulation use case the paper motivates.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 3] State the counter-case for the micro-optimizations that currently read as absolute (tip 42 <monospace>dim</monospace> vs <monospace>nrow</monospace>, tip 12 <monospace>mean</monospace> accuracy).</p>
  </list-item>
</list>
<p><sc>optional</sc>:</p>
<list list-type="bullet">
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
</list>
<p>We will correct these in production, and you confirm them in the proof:</p>
<list list-type="bullet">
  <list-item>
    <p>[consistency-check] The profiling output in Tip 2 lists a function <monospace>&quot;h&quot;</monospace> (self.time 0.01) that does not appear in the function <monospace>f</monospace> 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 <monospace>&quot;h&quot;</monospace> row has no source in the displayed code. Confirm the intended output.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 1] The R Inferno (Patrick Burns) is cited in the introduction but has no entry in the references. Supply the reference.</p>
  </list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r1-report1" article-type="reviewer-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r1.report1</article-id>
<title-group>
<article-title>Report Reviewer 1, round 1</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<collab>JRepStat review engine</collab>
<role specific-use="reviewer" content-type="reviewer-1">Reviewer 1</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="reviewer-report-received">
<event-desc>Reviewer report received</event-desc>
<date iso-8601-date="2026-09-27"><day>27</day><month>09</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>0</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>minor-revision</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><italic>Written by the journal&#x27;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 <ext-link ext-link-type="uri" xlink:href="https://jrepstat.fairpressjournals.com/about/peer-review/">peer review page</ext-link>.</italic></p>
<p>Recommendation: minor.</p>
<p>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.</p>
<p>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.</p>
<p>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 &gt; 0) for ifelse(x &gt; 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.</p>
<p>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.</p>
<p>Numbered suggestions to the authors:</p>
<list list-type="order">
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p>[editor_fix] Add a references entry for The R Inferno (P. Burns), which is cited in the introduction but missing from the reference list.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> Note in tip 36 that x * (x &gt; 0) and ifelse(x &gt; 0, x, 0) differ when x contains NA, so readers do not swap them blindly.</p>
  </list-item>
  <list-item>
    <p><sc>optional</sc> A short table grouping the tips by theme (memory, vectorization, matrix algebra, numerical stability) would make the tutorial easier to navigate and reference.</p>
  </list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r1-report2" article-type="reviewer-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r1.report2</article-id>
<title-group>
<article-title>Report Reviewer 2, round 1</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<collab>JRepStat review engine</collab>
<role specific-use="reviewer" content-type="reviewer-2">Reviewer 2</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="reviewer-report-received">
<event-desc>Reviewer report received</event-desc>
<date iso-8601-date="2026-09-27"><day>27</day><month>09</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>0</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>major-revision</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><italic>Written by the journal&#x27;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 <ext-link ext-link-type="uri" xlink:href="https://jrepstat.fairpressjournals.com/about/peer-review/">peer review page</ext-link>.</italic></p>
<p>Recommendation: major.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>Numbered suggestions to the authors:</p>
<list list-type="order">
  <list-item>
    <p><sc>required</sc> 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).</p>
  </list-item>
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p>[editor_fix] Make the tip count consistent: the abstract says “more than 100”, the title says “90+”, and the list ends at 94.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> Add collapse (fmean, fsum, fvar) to the grouped-operation tips 17 and 38, where it is typically faster than rowsum and aggregate.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>optional</sc> 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.</p>
  </list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r1-report3" article-type="reviewer-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r1.report3</article-id>
<title-group>
<article-title>Report Reviewer 3, round 1</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<collab>JRepStat review engine</collab>
<role specific-use="reviewer" content-type="reviewer-3">Reviewer 3</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="reviewer-report-received">
<event-desc>Reviewer report received</event-desc>
<date iso-8601-date="2026-09-27"><day>27</day><month>09</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>0</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>minor-revision</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><italic>Written by the journal&#x27;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 <ext-link ext-link-type="uri" xlink:href="https://jrepstat.fairpressjournals.com/about/peer-review/">peer review page</ext-link>.</italic></p>
<p>Recommendation: minor.</p>
<p>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.</p>
<p>The declared entry point is <monospace>Rscript R code.R</monospace>, 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 <monospace>microbenchmark(mean(x), ...)</monospace> with no <monospace>x</monospace> defined, chunk 5 uses <monospace>n</monospace>, chunk 6 uses <monospace>fast</monospace> and <monospace>slow</monospace>, and so on. No <monospace>set.seed</monospace> appears anywhere, so even the self-contained chunks that build data with <monospace>rnorm</monospace> 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.</p>
<p>Tip 17 has a correctness bug in its “a bit faster” variant. <monospace>rowsum(x, ina, reorder = FALSE)</monospace> returns group rows in order of first appearance, while <monospace>as.vector(table(ina))</monospace> returns counts in sorted factor-level order. When the two orders differ, each group mean is divided by another group’s count. The default <monospace>rowsum(x, ina)</monospace> in a2 is fine because it sorts. Please either align the counts to the <monospace>reorder = FALSE</monospace> order or drop a3. This belongs in a tutorial precisely because a reader will copy it.</p>
<p>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.</p>
<p>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 <monospace>princomp</monospace> over <monospace>prcomp</monospace> purely on timing. <monospace>princomp</monospace> forms the covariance and eigendecomposes it, which is less accurate for near-collinear data than the SVD route in <monospace>prcomp</monospace>, and one sentence should say so. On data.table, the paper uses it only through <monospace>fread</monospace>. For the aggregation tips (12 and 17) and for large grouped work generally, <monospace>[, by = ]</monospace>, 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.</p>
<p>Numbered suggestions to the authors:</p>
<list list-type="order">
  <list-item>
    <p><sc>required</sc> Make <monospace>R code.R</monospace> run end to end with inputs defined and <monospace>set.seed</monospace> 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.</p>
  </list-item>
  <list-item>
    <p><sc>required</sc> Fix tip 17: align <monospace>rowsum(x, ina, reorder = FALSE)</monospace> with counts in the same order, or remove the a3 variant, because dividing by <monospace>as.vector(table(ina))</monospace> uses sorted-order counts.</p>
  </list-item>
  <list-item>
    <p><sc>required</sc> Add a declaration of the authors’ interest in Rfast, Rfast2 and estats where those packages are recommended.</p>
  </list-item>
  <list-item>
    <p>[editor_fix] Reconcile the tip count: abstract and introduction say “more than 100”, the list ends at 94, and the title says “90+”.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> Add data.table beyond <monospace>fread</monospace>: keyed joins, grouped aggregation with <monospace>[, by = ]</monospace>, and update by reference, linked from tips 12 and 17.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> In tip 46, state that <monospace>princomp</monospace> is less accurate than <monospace>prcomp</monospace> for near-collinear data.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> In Section 9, add a note on reproducible parallel RNG using <monospace>clusterSetRNGStream</monospace> and <monospace>mc.set.seed</monospace>.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> Give the counter-case for the micro-optimizations that read as absolute, including tip 42 (<monospace>dim</monospace> vs <monospace>nrow</monospace>) and the accuracy cost in tip 12 (<monospace>mean</monospace> vs <monospace>sum(x)/length(x)</monospace>).</p>
  </list-item>
  <list-item>
    <p><sc>optional</sc> Add a short note on when to move to Rcpp or RcppArmadillo yourself, as a complement to the wrapper-package route.</p>
  </list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r1-response" article-type="author-comment">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r1.response</article-id>
<title-group>
<article-title>Authors&#x27; response, round 1</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<string-name>Michail Tsagris</string-name>
<role specific-use="author">Author</role>
</contrib>
<contrib contrib-type="author">
<string-name>Manos Papadakis</string-name>
<role specific-use="author">Author</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="author-comment-received">
<event-desc>Author comment received</event-desc>
<date iso-8601-date="2026-10-22"><day>22</day><month>10</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15.r1.letter" document-id-type="doi" document-type="editor-report"/>
<related-object document-id="10.68365/jrepstat.2026.15.r1.report1" document-id-type="doi" document-type="reviewer-report"/>
<related-object document-id="10.68365/jrepstat.2026.15.r1.report2" document-id-type="doi" document-type="reviewer-report"/>
<related-object document-id="10.68365/jrepstat.2026.15.r1.report3" document-id-type="doi" document-type="reviewer-report"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>0</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p>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&#x27;s reports say what remains open.</p>
<p>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?</p>
<list list-type="simple">
<list-item>
<p><sc>required</sc> The abstract and the introduction both state &quot;more than 100 tips&quot;, but the body contains 94 numbered tips (1 through 94, the last being the `[[` versus `$` item in Section 11). The title says &quot;90+ tips&quot;, which matches the count. Reconcile the abstract and the two introduction sentences (&quot;a collection of more than 100 tips&quot;, &quot;We have listed more than 100 tips&quot;) with the actual number so the claim agrees with the title and the content.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> Tip 64 states that prcomp() &quot;performs the eigendecomposition of a matrix&quot;. 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> Add a competing-interest statement. The authors maintain Rfast, Rfast2 and estats, which the paper recommends as faster (tips 64, 72, Section 10).</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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 &quot;an alternative to base R&quot;.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> Add data.table coverage beyond `fread`: keyed joins, grouped aggregation with `[, by = ]`, and update by reference, cross-referenced from tips 12 and 17.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> A short note on when to leave base R for Rcpp or RcppArmadillo yourself, not only via a wrapper package.</p>
<p><bold>Done.</bold></p>
</list-item>
</list>
<supplementary-material id="pr-r1-letter-file" xlink:href="taking-r-to-its-limits-90-tips-response-round1.pdf" mimetype="application" mime-subtype="pdf">
<caption>
<p>The authors' full response letter to round 1, as uploaded.</p>
</caption>
</supplementary-material>
</body>
</sub-article>
<sub-article id="pr-r2-letter" article-type="editor-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r2.letter</article-id>
<title-group>
<article-title>Decision letter, round 2</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<contrib-id contrib-id-type="orcid">https://orcid.org/0000-0002-8638-5276</contrib-id>
<string-name>Matthias Templ</string-name>
<role specific-use="editor">Editor</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="editor-decision-sent">
<event-desc>Editor decision sent</event-desc>
<date iso-8601-date="2026-10-22"><day>22</day><month>10</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>1</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>minor-revision</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><bold>Minor revision.</bold> Confirmed and signed by Matthias Templ on 2026-10-22.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p><sc>required</sc> (the decision rests on these):</p>
<list list-type="bullet">
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[theory-and-proofs] Tip 17 option a3 still misaligns in the same family of cases the prior round flagged. The author removed <monospace>reorder = FALSE</monospace>, so <monospace>rowsum(x, ina)</monospace> now returns groups in sorted order and divides by <monospace>as.vector(tabulate(ina))</monospace>. This agrees only when the group codes are the consecutive positive integers 1..k. When the codes have a gap, say <monospace>ina = c(1,3,3,1)</monospace>, <monospace>rowsum</monospace> returns two rows while <monospace>tabulate(ina)</monospace> returns <monospace>c(2,0,2)</monospace> of length three, and the division recycles, so each group mean is divided by the wrong count. Option a2 with <monospace>table(ina)</monospace> is safe because <monospace>table</monospace> returns only present levels in sorted order. Either drop a3, or add the “consecutive strictly positive integers” caveat that Tip 16 already states for <monospace>tabulate</monospace> and cross-reference it.</p>
  </list-item>
  <list-item>
    <p>[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.”</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 3] Add data.table coverage beyond <monospace>fread</monospace>: keyed joins, grouped aggregation with <monospace>[, by = ]</monospace>, and update by reference, cross-referenced from tips 12 and 17. This was asked in the previous round and is still open.</p>
  </list-item>
</list>
<p><sc>recommended</sc>:</p>
<list list-type="bullet">
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 3] Name the BLAS in the paper text, not only LAPACK 3.12.1, since the matrix timings depend on it.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[Reviewer 3] State the counter-case for the micro-optimizations that currently read as absolute (tip 42 <monospace>dim</monospace> vs <monospace>nrow</monospace>, tip 12 <monospace>mean</monospace> accuracy). This was asked in the previous round and is still open.</p>
  </list-item>
</list>
<p><sc>optional</sc>:</p>
<list list-type="bullet">
  <list-item>
    <p>[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.</p>
  </list-item>
</list>
<p>We will correct these in production, and you confirm them in the proof:</p>
<list list-type="bullet">
  <list-item>
    <p>[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.</p>
  </list-item>
  <list-item>
    <p>[writing-quality] Tip 19 (incremental calculations): “the first–rder partial correlations” is missing a letter and reads as “first-order”. Confirm in the proof.</p>
  </list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r2-report1" article-type="reviewer-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r2.report1</article-id>
<title-group>
<article-title>Report Reviewer 1, round 2</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<collab>JRepStat review engine</collab>
<role specific-use="reviewer" content-type="reviewer-1">Reviewer 1</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="reviewer-report-received">
<event-desc>Reviewer report received</event-desc>
<date iso-8601-date="2026-10-22"><day>22</day><month>10</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>1</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>minor-revision</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><italic>Written by the journal&#x27;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 <ext-link ext-link-type="uri" xlink:href="https://jrepstat.fairpressjournals.com/about/peer-review/">peer review page</ext-link>.</italic></p>
<p>Recommendation: minor.</p>
<p>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 <monospace>x * (x &gt; 0)</monospace> and <monospace>ifelse</monospace>. 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.</p>
<p>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 <monospace>crossprod</monospace>, <monospace>solve</monospace>, <monospace>eigen</monospace>, <monospace>princomp</monospace> and the <monospace>float</monospace> 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 <monospace>prcomp</monospace> beat <monospace>princomp</monospace>, which is exactly the caveat that belongs in the text. I have marked this recommended because the shipped environment covers the verifiable minimum.</p>
<p>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.</p>
<p>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.</p>
<p>Numbered suggestions to the authors:</p>
<list list-type="order">
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> 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 <monospace>crossprod</monospace> versus explicit transpose-multiply, <monospace>princomp</monospace> versus <monospace>prcomp</monospace>, and the <monospace>float</monospace> tip can narrow or reverse under OpenBLAS or MKL.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> 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.</p>
  </list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r2-report2" article-type="reviewer-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r2.report2</article-id>
<title-group>
<article-title>Report Reviewer 2, round 2</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<collab>JRepStat review engine</collab>
<role specific-use="reviewer" content-type="reviewer-2">Reviewer 2</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="reviewer-report-received">
<event-desc>Reviewer report received</event-desc>
<date iso-8601-date="2026-10-22"><day>22</day><month>10</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>1</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>minor-revision</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><italic>Written by the journal&#x27;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 <ext-link ext-link-type="uri" xlink:href="https://jrepstat.fairpressjournals.com/about/peer-review/">peer review page</ext-link>.</italic></p>
<p>Recommendation: minor.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>Numbered suggestions to the authors:</p>
<list list-type="order">
  <list-item>
    <p><sc>required</sc> 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.”</p>
  </list-item>
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> 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.</p>
  </list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r2-report3" article-type="reviewer-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r2.report3</article-id>
<title-group>
<article-title>Report Reviewer 3, round 2</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<collab>JRepStat review engine</collab>
<role specific-use="reviewer" content-type="reviewer-3">Reviewer 3</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="reviewer-report-received">
<event-desc>Reviewer report received</event-desc>
<date iso-8601-date="2026-10-22"><day>22</day><month>10</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>1</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>minor-revision</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><italic>Written by the journal&#x27;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 <ext-link ext-link-type="uri" xlink:href="https://jrepstat.fairpressjournals.com/about/peer-review/">peer review page</ext-link>.</italic></p>
<p>Recommendation: minor.</p>
<p>Of the three required points and six lighter ones I raised, two of the three required are met and one is still open.</p>
<p>The tip 17 correctness bug is fixed. The a3 variant now reads <monospace>rowsum(x, ina) / as.vector(tabulate(ina))</monospace>, and the default <monospace>rowsum</monospace> sorts numeric group labels numerically, so for the consecutive positive-integer grouping that <monospace>tabulate</monospace> 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 <monospace>mean</monospace> 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.</p>
<p>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.</p>
<p>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 <monospace>sessionInfo()</monospace> 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.</p>
<p>Numbered suggestions to the authors:</p>
<list list-type="order">
  <list-item>
    <p><sc>required</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> 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.</p>
  </list-item>
  <list-item>
    <p><sc>recommended</sc> In Section 9, add a note on reproducible parallel RNG using <monospace>clusterSetRNGStream</monospace> and <monospace>mc.set.seed</monospace>, aimed at reproducing simulation results rather than timings.</p>
  </list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r2-response" article-type="author-comment">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r2.response</article-id>
<title-group>
<article-title>Authors&#x27; response, round 2</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<string-name>Michail Tsagris</string-name>
<role specific-use="author">Author</role>
</contrib>
<contrib contrib-type="author">
<string-name>Manos Papadakis</string-name>
<role specific-use="author">Author</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="author-comment-received">
<event-desc>Author comment received</event-desc>
<date iso-8601-date="2026-11-09"><day>09</day><month>11</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15.r2.letter" document-id-type="doi" document-type="editor-report"/>
<related-object document-id="10.68365/jrepstat.2026.15.r2.report1" document-id-type="doi" document-type="reviewer-report"/>
<related-object document-id="10.68365/jrepstat.2026.15.r2.report2" document-id-type="doi" document-type="reviewer-report"/>
<related-object document-id="10.68365/jrepstat.2026.15.r2.report3" document-id-type="doi" document-type="reviewer-report"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>1</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p>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&#x27;s reports say what remains open.</p>
<p>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.</p>
<list list-type="simple">
<list-item>
<p><sc>required</sc> The nearest prior work is the authors&#x27; own earlier preprint &quot;Taking R to its limits: 70+ tips&quot; (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 &quot;to the best of our knowledge, this is the first time such a long list has been compiled in one place,&quot; and the response letter itself refers to &quot;an earlier version of this paper, which can be found on the web.&quot; 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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 &quot;consecutive strictly positive integers&quot; caveat that Tip 16 already states for `tabulate` and cross-reference it.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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 (&quot;We will ask the editors what to write and where&quot;) 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: &quot;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.&quot;</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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 &quot;an alternative to base R&quot;. This was asked in the previous round and is still open.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>recommended</sc> The reproducible parallel RNG note (Section 9) is still absent. The decline rests on timing, but the point is reproducibility of simulation results.</p>
<p><bold>Declined.</bold> We argue against it because the goal is on the time comparisons, not the reproducibility of some random number that do not affect time.</p>
</list-item>
<list-item>
<p><sc>recommended</sc> Add collapse (fmean, fsum, fvar) to the grouped-operation tips (17, 38). This was asked in the previous round and is still open.</p>
<p><bold>Declined.</bold> If we add them then we would have to add many more in other tips.</p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> Add a competing-interest statement. The authors maintain Rfast, Rfast2 and estats, which the paper recommends as faster (tips 64, 72, Section 10).</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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 &quot;an alternative to base R&quot;.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> 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.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>required</sc> Add data.table coverage beyond `fread`: keyed joins, grouped aggregation with `[, by = ]`, and update by reference, cross-referenced from tips 12 and 17.</p>
<p><bold>Done.</bold></p>
</list-item>
<list-item>
<p><sc>recommended</sc> Add collapse (fmean, fsum, fvar) to the grouped-operation tips (17, 38).</p>
<p><bold>Declined.</bold> If we add them then we would have to add many more in other tips.</p>
</list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r3-letter" article-type="editor-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r3.letter</article-id>
<title-group>
<article-title>Decision letter, round 3</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<contrib-id contrib-id-type="orcid">https://orcid.org/0000-0002-8638-5276</contrib-id>
<string-name>Matthias Templ</string-name>
<role specific-use="editor">Editor</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="editor-decision-sent">
<event-desc>Editor decision sent</event-desc>
<date iso-8601-date="2026-11-14"><day>14</day><month>11</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>2</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>accept</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><bold>Accepted.</bold> Signed by Matthias Templ on 2026-11-14.</p>
<p>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.</p>
<p>Congratulations, your manuscript has been accepted for publication in JRepStat. Production begins now.</p>
<p>Where it is not on file yet, we still need the following for production.</p>
<list list-type="bullet">
  <list-item>
    <p>a valid ORCID iD for every author</p>
  </list-item>
  <list-item>
    <p>a captured computational environment (dependencies/lockfile/container)</p>
  </list-item>
  <list-item>
    <p>a signed determinism attestation for the entry-point command</p>
  </list-item>
</list>
</body>
</sub-article>
<sub-article id="pr-r3-report1" article-type="reviewer-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r3.report1</article-id>
<title-group>
<article-title>Report Reviewer 1, round 3</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<collab>JRepStat review engine</collab>
<role specific-use="reviewer" content-type="reviewer-1">Reviewer 1</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="reviewer-report-received">
<event-desc>Reviewer report received</event-desc>
<date iso-8601-date="2026-11-09"><day>09</day><month>11</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>2</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>accept</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><italic>Written by the journal&#x27;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 <ext-link ext-link-type="uri" xlink:href="https://jrepstat.fairpressjournals.com/about/peer-review/">peer review page</ext-link>.</italic></p>
<p>Recommendation: accept.</p>
<p>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.</p>
<p>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.</p>
<p>Nothing remains open, and the paper reads cleanly as it now stands.</p>
<p>Numbered suggestions to the authors:</p>
<p>(none)</p>
</body>
</sub-article>
<sub-article id="pr-r3-report2" article-type="reviewer-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r3.report2</article-id>
<title-group>
<article-title>Report Reviewer 2, round 3</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<collab>JRepStat review engine</collab>
<role specific-use="reviewer" content-type="reviewer-2">Reviewer 2</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="reviewer-report-received">
<event-desc>Reviewer report received</event-desc>
<date iso-8601-date="2026-11-09"><day>09</day><month>11</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>2</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>accept</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><italic>Written by the journal&#x27;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 <ext-link ext-link-type="uri" xlink:href="https://jrepstat.fairpressjournals.com/about/peer-review/">peer review page</ext-link>.</italic></p>
<p>Recommendation: accept.</p>
<p>Of the three points I raised, all are met.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>Nothing is open.</p>
<p>Numbered suggestions to the authors:</p>
<p>(none)</p>
</body>
</sub-article>
<sub-article id="pr-r3-report3" article-type="reviewer-report">
<front-stub>
<article-id pub-id-type="doi">10.68365/jrepstat.2026.15.r3.report3</article-id>
<title-group>
<article-title>Report Reviewer 3, round 3</article-title>
</title-group>
<contrib-group>
<contrib contrib-type="author">
<collab>JRepStat review engine</collab>
<role specific-use="reviewer" content-type="reviewer-3">Reviewer 3</role>
</contrib>
</contrib-group>
<pub-history>
<event event-type="reviewer-report-received">
<event-desc>Reviewer report received</event-desc>
<date iso-8601-date="2026-11-09"><day>09</day><month>11</month><year>2026</year></date>
</event>
</pub-history>
<related-object document-id="10.68365/jrepstat.2026.15" document-id-type="doi" document-type="peer-reviewed-article"/>
<custom-meta-group>
<custom-meta><meta-name>peer-review-stage</meta-name><meta-value>pre-publication</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-revision-round</meta-name><meta-value>2</meta-value></custom-meta>
<custom-meta><meta-name>peer-review-recommendation</meta-name><meta-value>accept</meta-value></custom-meta>
</custom-meta-group>
</front-stub>
<body>
<p><italic>Written by the journal&#x27;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 <ext-link ext-link-type="uri" xlink:href="https://jrepstat.fairpressjournals.com/about/peer-review/">peer review page</ext-link>.</italic></p>
<p>Recommendation: accept.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>Numbered suggestions to the authors:</p>
<list list-type="order">
  <list-item>
    <p><sc>optional</sc> 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.</p>
  </list-item>
</list>
</body>
</sub-article>
</article>
