如何从函数中获取输出?

时间:2013-03-09 20:40:57

标签: r function return-value

我将代码list(Root = xnew, Value = f(xnew), Iterations=i)添加到以下函数的末尾,以便将Root,Value和Iterations全部打印出来,但我只得到一个值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")
}

1 个答案:

答案 0 :(得分:0)

回答去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")
}