Martin Maechler
2005-Dec-20 17:51 UTC
[Rd] pmin(), pmax() - slower than necessary for common cases
A few hours ago, I was making a small point on the R-SIG-robust mailing list on the point that ifelse() was not too efficient in a situation where pmax() could easily be used instead. However, this has reminded me of some timing experiments that I did 13 years ago with S-plus -- where I found that pmin() / pmax() were really relatively slow for the most common case where they are used with only two arguments {and typically one of the arguments is a scalar; but that's not even important here}. The main reason is that the function accept an arbitrary number of arguments and that they do recycling. Their source is at https://svn.R-project.org/R/trunk/src/library/base/R/pmax.R In April 2001 (as I see), I had repeated my timings with R (1.2.2) which confirmed the picture more or less, but for some reason I never drew "proper" consequences of my findings. Of course one can argue pmax() & pmin() are still quite fast functions; OTOH the experiment below shows that -- at least the special case with 2 (matching) arguments could be made faster by about a factor of 19 ... I don't have yet a constructive proposition; just note the fact that pmin. <- function(k,x) (x+k - abs(x-k))/2 pmax. <- function(k,x) (x+k + abs(x-k))/2 are probably the fastest way of computing pmin() and pmax() of two arguments {yes, they "suffer" from rounding error of about 1 to 2 bits...} currently in R. One "solution" could be to provide pmin2() and pmax2() functions based on trival .Internal() versions. The experiments below are for the special case of k=0 where I found the above mentioned factor of 19 which is a bit overoptimistic for the general case; here is my pmax-ex.R source file (as text/plain attachment ASCII-code --> easy cut & paste) demonstrating what I claim above. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: pmax-ex.R Url: https://stat.ethz.ch/pipermail/r-devel/attachments/20051220/1cca8998/pmax-ex.pl -------------- next part -------------- Martin Maechler, ETH Zurich
Reasonably Related Threads
- override pmin/pmax for my own matrix
- override pmin/pmax for my own matrix
- There is pmin and pmax each taking na.rm, how about psum?
- minor error in documentation of pmax in base (PR#2513)
- predict.glm(..., type="response") dropping names (and a propsed (PR#7792)