[R] Calling Function With Arguments In a Script

Bert Gunter gunter.berton at gene.com
Thu May 7 23:44:30 CEST 2015


See e.g. Chapter 10.4 in the "Intro to R Tutorial" on the "..." argument.

The general idea is to define your function as:

myfun <- function (named_arguments,...)
{
# Some code
## now call your function as
pairwisePlot(some_named_arguments,...)
}

You would then call myfun with the ...'s replaced by name=value
argument pairs for your pairwisePlot function. e.g.

myfun(named_arguments, arg1= value1, arg2=value2, etc.)

where the arg1, arg2, etc. arguments would be arguments for
pairwisePlot() passed down to it as ... arguments.

Not hard, really, once you see how it works. (I suppose that's a
tautology, though -- probably what physicists say about General
Relativity).

Incidentally, you could even have functions as arbitrary arguments to
myfun and ... contain the argument lists for the function, something
like:

myfunc <- function(fun,...) {fun(...) }

Think of the flexibility this gives! One of the glories of functional
programming -- functions are first class objects that can be used as
arguments just like anything else.

Cheers,
Bert


Bert Gunter
Genentech Nonclinical Biostatistics
(650) 467-7374

"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
Clifford Stoll




On Thu, May 7, 2015 at 1:50 PM, Rich Shepard <rshepard at appl-ecosys.com> wrote:
>   I'm starting to put code in multi-use functions rather than in individual
> scripts and have not learned how to invoke the function from the command
> line. If this information is in Norman Matloff's 'The Art of R Programming'
> or Hadley Wickham's 'Advanced R' please point me to the proper place.
>
>   Here's an example, the script 'pairwise-plots-continuous-vars.R' consists
> of this function:
>
> plotpairs <- function(x1,x2,x3,y,plotmain) {
>     require(compositions)
>     opar <- par(mar=c(4,4,3,1))
>     NO3 <- x1
>     SO4 <- x2
>     pH <- x3
>     pairwisePlot(cbind(NO3,SO4,pH),clr(y),add.line=T)
>     title(main=plotmain)
>     par(opar)
>     detach('package:compositions')
>     return()
> }
>
>   (I suppose the return statement is superfluous since there is no value
> returned to a calling function.)
>
>   What I want to do is call plotpairs() with appropriate arguments for each
> plot as needed.
>
> TIA,
>
> Rich
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list