Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: is there a way to capture all the function argument values

I wrote a function that makes plots. One of the problems I encounter is the need to produce reproducible graphs. One solution is, of course, save the code for each plot I produce (i.e., save the exact values I set for the function arguments). I wonder however if there is a way in which I can capture all the input values, including the data object, etc, and save them in a list and return it as an output. A simple way to do it, I suppose, is as follows:

plot.foo <- function(x, main=NULL){
    plot(x, main=main)
    list(data=x, main=main)
}

However, the function I wrote has a bunch of arguments in addition to an ellipsis argument (see below), so I wonder if there is a quicker way to save all the input argument values. Thanks!

plot.foo <- function(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10,...){
     ...
}
like image 655
Alex Avatar asked Mar 13 '13 17:03

Alex


2 Answers

There are a variety of functions that may be useful: match.call, match.arg and then there are specific methods for extracting the ... arguments.

plot.foo <- 
   function(x, main=NULL){ 
     cl <- match.call()
     print(cl)
     plot(x, main=main)
     list(data=x, main=main)
   }

plot.foo(1)
## plot.foo(x = 1)
## $data
## [1] 1
## 
## $main
## NULL

plot.foo <- 
  function(x, main=NULL, ...){ 
    extras=list(...)
    print(extras)

    cl <- match.call()   
    print(cl)

    plot(x, main=main)  # this would actually produce the grapjic
    list(data=x, main=main, extras=extras) # this returns the arguments as a list
   }

plot.foo(1, sthg="z")
## $sthg
## [1] "z"

# You could assign the returned list to a name or you could `save` to a file
plot.foo(x = 1, sthg = "z")
## $data
## [1] 1
## 
## $main
## NULL

There is also the sys.call function whose result could be returned as text with deparse.

like image 65
IRTFM Avatar answered Oct 06 '22 03:10

IRTFM


From the start, make a named list of all your plot arguments

L <- list(x=data, main="string", ylim=c(0,10))

Then plot using that object as the set of parameters

do.call("plot", L)

Make sure to save L for later use.

Working example:

L<-list(x=1:10, y=(1:10)^2, main="Y by X",type="l",xlab="X",ylab="Y")
do.call("plot",L)
like image 27
ndoogan Avatar answered Oct 06 '22 04:10

ndoogan