【问题标题】:R - Change return values of existing functionR - 更改现有函数的返回值
【发布时间】:2017-12-05 19:28:57
【问题描述】:

我正在使用 approxfun() 函数来获得线性插值。我想编写一个函数,它获取 approxfun() 的结果,然后按我指定的量移动和缩放它。我需要能够像调用任何其他函数一样调用这个新函数。

我的尝试的简化版:

set.seed(42)
x = rnorm(50)
y = rnorm(50, 5, 2)
fhat = approxfun(x, y, rule = 2)

new_function = function(fhat, a, b){

  new_fhat <- (function(fhat, a, b) a * fhat() + b)()

  return(new_fhat)

}

我希望结果是一样的

2 * fhat(1) + 3

但是当我运行我的函数时

new_function(fhat, a = 2, b = 3)

我收到一条错误消息:

* (function(fhat, a, b) a * fhat() + b)() 中的错误: 缺少参数“a”,没有默认值*

【问题讨论】:

    标签: r function functional-programming statistics


    【解决方案1】:

    你有四个问题:

    1. new_fhat 没有从new_function 调用中传递ab 的值,并且看不到它们,因为您正在函数定义中创建新值。这实际上是一个红鲱鱼,因为...
    2. 您返回的函数应该只有一个参数 - 您要评估它的点。
    3. 您正在尝试立即评估 new_fhat
    4. 您正在尝试不带参数地调用 fhat

    解决办法是:

    new_function = function(fhat, a, b){
    
      new_fhat <- function(v) a * fhat(v) + b
    
      return(new_fhat)
    
    }
    

    结果:

    fhat(1)
    [1] 5.31933
    new_function(fhat,a=2,b=3)(1)
    [1] 13.63866
    2 * fhat(1) + 3
    [1] 13.63866
    

    【讨论】:

      【解决方案2】:

      这相当于问题中的代码,但简化了:

      new_function = function(fhat, a, b) {
        a * fhat() + b
      }
      

      但这不正确,因为在发布的代码中fhat 需要一个参数。例如,要使new_function(fhat, a = 2, b = 3) 返回与2 * fhat(1) + 3 相同的结果,您必须在函数中添加参数 1:

      new_function = function(fhat, a, b) {
        a * fhat(1) + b
      }
      

      【讨论】:

        猜你喜欢
        • 2014-02-27
        • 1970-01-01
        • 1970-01-01
        • 2015-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多