有没有一种方法可以捕获所有函数参数值?

16

我写了一个制作图表的函数。我遇到的一个问题是需要生成可重现的图形。其中一种解决方案当然是保存我为每个绘图设置的确切值的代码(即保存函数参数的确切值)。然而,我想知道是否有一种方法可以捕获所有输入值,包括数据对象等,并将它们保存在列表中并将其作为输出返回。一种简单的方法,我想如下:

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

然而,我写的函数除了省略号参数(见下文)之外还有一堆其他参数,所以我想知道是否有更快的方法来保存所有的输入参数值。谢谢!

plot.foo <- function(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10,...){
     ...
}
2个回答

18

有许多可能会有用的函数: match.call, match.arg 还有特定的提取...参数的方法。

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

此外还有sys.call函数,其结果可以通过deparse函数返回为文本。


8
从一开始,制作一个命名列表,列出所有您的情节参数。
L <- list(x=data, main="string", ylim=c(0,10))

然后使用该对象作为参数集进行绘图。
do.call("plot", L)

请确保将 L 保存以备后用。

以下是示例:

L<-list(x=1:10, y=(1:10)^2, main="Y by X",type="l",xlab="X",ylab="Y")
do.call("plot",L)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接