Reputation: 4180
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,...){
...
}
Upvotes: 16
Views: 6850
Reputation: 263301
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
.
Upvotes: 18
Reputation: 1925
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)
Upvotes: 8