Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are `colMeans()` and `rowMeans()` functions faster than using the mean function with `lapply()`?

What I want to ask is, algorithmically, what do the rowMeans() and colMeans() functions do to optimize speed?

like image 673
user1482678 Avatar asked Oct 19 '25 04:10

user1482678


1 Answers

In addition, consider what lapply() does. It sets up repeated calls to the function mean(). So as well as the overhead of actually computing a mean (which is done in fast C code), the lapply() version repeatedly incurs the overhead of the sanity checking code and method dispatch associated with mean().

rowMeans() and colMeans() incur only a single set of sanity checks as internally, their C code is optimised to loop over the rows/columns there rather than via separate R calls.

like image 132
Gavin Simpson Avatar answered Oct 21 '25 19:10

Gavin Simpson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!