【问题标题】:How to get output from a function?如何从函数中获取输出?
【发布时间】:2013-03-09 20:40:56
【问题描述】:

我将代码list(Root = xnew, Value = f(xnew), Iterations=i) 添加到以下函数的末尾以打印出所有根、值和迭代,但我只得到一个值,即xnew。我该如何解决这个问题?

fixedpoint <- function(fun, x0, tol=1e-08, max.iter=40){
    xold <- x0
    xnew <- fun(xold)
    for (i in 1:max.iter) {
    xold <- xnew
    xnew <- f(xold)
    if ( abs((xnew-xold)) < tol )
        return(xnew)
    }
    stop("max iterations = 20")
}

【问题讨论】:

  • 注意函数中已经存在的return语句...
  • 我把 "(Root = xnew, Value = f(xnew), Iterations=i)" 放在了 return 里面但是得到了一个警告信息:In return(Root = x2, Value = f(x2), Iterations = i) :不推荐使用多参数返回。
  • return(list(Root = xnew, Value = f(xnew), Iterations=i))

标签: r function return-value


【解决方案1】:

回答到 N8TRO。

您应该将fixedpoint 返回值连接到list。请看下图:

fixedpoint <- function(fun, x0, tol = 1e-08, max.iter = 40) {
  xold <- x0
  xnew <- fun(xold)
  for (i in 1:max.iter) {
    xold <- xnew
    xnew <- f(xold)
    if (abs(xnew-xold) < tol) {
        return(list(Root = xnew, Value = f(xnew), Iterations = i))
  }
  stop("max iterations = 20")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 2017-09-03
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    相关资源
    最近更新 更多