【问题标题】:How to avoid re-listing internal function arguments in wrapper function in R?如何避免在 R 的包装函数中重新列出内部函数参数?
【发布时间】:2017-09-08 11:12:56
【问题描述】:

假设我有一个带有许多参数的函数(例如,plot())。

我想通过围绕该函数创建一个包装函数来为该函数添加一些功能。

  • 随机示例:

    plot.new <- function() {
      windows(width = 10, height = 10)
      plot()
    }
    

我的问题:如何才能在我的新包装函数中提供内部函数的参数?

  • 在定义包装函数时,如何在不重新键入内部函数中的所有参数名称的情况下这样做?

【问题讨论】:

    标签: r function arguments parameter-passing wrapper


    【解决方案1】:

    您可以使用three dots ellipsis

    plot.new <- function(...) {
      windows(width = 10, height = 10)
      plot(...)
    }
    

    如果您想在包装函数列表中显式包含任何内部函数参数,您还必须在内部函数中显式定义该参数:

    plot.new <- function(x, ...) {
        graphics.off() #OPTIONAL
        windows(width = 10, height = 10)
        plot(x = x, ...)
    }
    
    #USAGE
    plot.new(x = rnorm(10), y = rnorm(10), pch = 19)
    

    And here is more discussion on using to distribute the arguments to multiple internal functions.

    【讨论】:

    • 它们是否需要出现在两个参数列表位置?
    • 如果我“重用”一个参数名称(或选择只定义一个内部函数的参数)会发生什么?例如:plot.new &lt;- function(x,...) { plot(...) }
    • 最后一个问题:我可以将省略号放在包装函数参数列表中的任何位置吗?例如:function(...,z)function(z,...)?如果是这样,如果我在运行包装函数时选择不命名参数,这是否会指示参数的“排序”?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多