R:有没有办法捕获所有函数参数值

标签 r function arguments

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

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,...){
     ...
}

最佳答案

有多种可能有用的函数: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 .

关于R:有没有办法捕获所有函数参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15391943/

相关文章:

r - data.table 行引用行为

javascript - 如何推断变量使它们成为全局变量?

bash - 将参数传递给 bash 函数时 "$@"和 "$*"之间的区别

assembly - 为什么 pop 在汇编中需要一个参数?

逐行应用 rvest html_nodes() 并将输出存储在新列中

r - 如何通过 setwd() 使用变量?

r - 自定义缩放轴后ggplot2缺少标签

function - 函数长度应该有多大(函数中的代码行)?

excel - Excel VBA中.Delete和.Clear之间的区别?

javascript - 在 JavaScript 中哪里执行参数验证?