[R] default arguments and '...' in a function

Gabor Grothendieck ggrothendieck at gmail.com
Thu Dec 2 03:39:15 CET 2010


On Wed, Dec 1, 2010 at 2:34 PM,  <Antonio.Gasparrini at lshtm.ac.uk> wrote:
> Dear R-users,
>
> I'm trying to work out a way to set default values for arguments in a function which includes the optional argument '...'.
> In practice, I have a 'plot' method for a function which specifies different types of plots. Every different plot should have different default arguments (for example for 'col', 'ylim' etc), plus the argument '...' to leave further optional choices to the user.
> My problem is that I need to specify a large number of arguments in the usage (losing clarity), or alternatively leaving to the user the specification of an high number of argument (adding complexity).
>
> An example.
> Suppose I want to create a function f with arguments 'a', and '...'.
> Two more arguments 'b' and 'c' should be both set to 1 by default if the user don't include them in '...'.
>
> f <- function(a,...) {
>  # set b <- 1 if b is not included in '...'
>  # set c <- 1 if c is not included in '...'
>  somefunction(a,b,c,...)
> }
>


Try using modifyList as shown:

# simple function for illustration
somefunction <- function(a, b, c) sprintf("a: %d, b: %d, c: %d", a, b, c)

f <- function(a, ...) {
   L <- modifyList(list(b = 1, c = 1), list(a = a, ...))
   do.call(somefunction, L)
}

f(5, c = 3) # "a: 5, b: 1, c: 3"

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list