[Rd] extendrange(): suggested improvement

Martin Maechler maechler at stat.math.ethz.ch
Thu Apr 26 10:55:30 CEST 2018


>>>>> Marius Hofert <marius.hofert at uwaterloo.ca>
>>>>>     on Wed, 25 Apr 2018 17:31:01 -0400 writes:

    > Hi,
    > I often need to extend the plot range to the right, but not to the
    > left (for example: not below 0 so that log = "x" still works...). This
    > could be a handy improvement of extendrange():

>     --- utils.R 2015-08-25 18:18:20.000000000 -0400
>     +++ utils.R 2018-04-25 17:21:25.000000000 -0400
>     @@ -30,6 +30,6 @@
> 	 ## Purpose: extend a range by a factor 'f' - on each side
> 	 if(!missing(r) && length(r) != 2)
> 	     stop("'r' must be a \"range\", hence of length 2")
>     -    r + c(-f,f) * diff(r)
>     -
>     +    if(length(f) == 1) f <- rep(f, 2)
>     +    r + c(-f[1], f[2]) * diff(r)
>      }


Yes, you are right and it's not the first time I've heard/seen
this wish.
Thank you for the suggestion!

I'd go for the more elegant (faster, at least in default case?) 
version


extendrange <- function(x, r = range(x, na.rm = TRUE), f = 0.05)
{
    ## Purpose: extend a range by a factor 'f' - on each side
    if(!missing(r) && length(r) != 2)
        stop("'r' must be a \"range\", hence of length 2")
    f <- if(length(f) == 1L) c(-f,f) else c(-f[1L], f[2L])
    r + f * diff(r)
}

PS:
/* I hope the tidy faction will at some time be convinced that
  using  if()  as a *function* in R is elegant and *the* R-way: 
  R is as functional a language as possible and hereby differs
  from C and similar languages ! 
*/

Martin Maechler
ETH Zurich



More information about the R-devel mailing list