【问题标题】:How can I return a plot from for loop in R?如何从 R 中的 for 循环返回绘图?
【发布时间】:2018-05-04 04:23:24
【问题描述】:

我正在尝试为二分法编写程序,并尝试在每次迭代时也绘制点。

这是我尝试过的代码。

Bisec = function(f,a =1, b =2, max=1e10, tol = 1e-100){
  midVals = c()
  for (i in 1:max){
    c = (a+b)/2
    midVals = append(midVals,c)
    if(abs(f(c)) < tol){
      return(list(c,plot(f),points(midVals)))
    }else if(f(a)*f(c) > 0){
    a = c  
    }else{
      b =c 
    }
      }
  print("Maximum iterations reached")
}
x = var('x')
f = function(x){x*x-2}
Bisec(f,1, 3, max=1e5, tol = 1e-10)

但是我得到了这样的图表。

我需要什么?

  • 必须绘制函数 f。
  • 在每次迭代中找到的中点应绘制在 x 轴上。

如何做到这一点?

任何提示都可能会有所帮助。我不知道我哪里错了。

【问题讨论】:

  • 试试 return(list(c,plot(f),midVals))x &lt;- Bisec(f,1, 3, max=1e5, tol = 1)plot(x[[2]]$x, x[[2]]$y, type="l", xlim=c(0,3)) points(x[[3]])。但我不知道你对你的观点有什么期望。 `
  • @StéphaneLaurent 我收到此错误Error: unexpected symbol in "plot(x[[2]]$x, x[[2]]$y, type="l", xlim=c(0,3)) points"
  • @StéphaneLaurent 关于points(midVals):我试图在 xaxis 上显示迭代中计算的中点。
  • 这里的问题离题了吗?应该移到codereview.stackexchange.com 吗?
  • 不,codereview 是针对工作代码的。

标签: r plot return


【解决方案1】:

如果你学会了用不同的语言编程,R 符号可能会有点不同。 R 的部分功能在于它集成了解释接口和(快速)编译函数。通常(虽然这可能是一个例外,但我并不关注这一点),避免for 循环(许多函数是矢量化的,这意味着它们在代码的编译部分中执行循环)。我们还避免定义空变量,因为每次您想向它们添加内容时都必须复制和粘贴它们。

对于您的具体问题,plot 正在绘制 f - 它只是对 points 命令一无所知,因为它在看到 points 之前会评估 plot .您可能会发现 ggplot2 提供了一个更动态的解决方案,但我将从您的函数的基本 R 方法开始:

Bisec = function(f,a =1, b =2, max_iter=1e10, tol = 1e-100){
  midVals = rep(NA, max_iter) # I avoid using `max` since that's a function to find the maximum

  for (i in 1:max_iter){
    x <- mean(c(a,b)) # I also avoid using `c` since that's a function to concatenate stuff
    midVals[i] <- x

    if(abs(f(x)) < tol){
      plot(f, xlim = range(midVals, na.rm = TRUE))
      points(midVals, rep(0,length(midVals))
      return(x)
    } else if(f(a)*f(x) > 0){
    a = x  
    }
    else{
      b = x 
    }
  }
  print("Maximum iterations reached")
}

【讨论】:

  • 只是出于好奇...` na.rm = TRUE` 在绘图时删除值 `NA 对吗??
  • 可能是for循环中的打印错误? ..max = max_iter
  • 我收到此错误Error in x * x : non-numeric argument to binary operator
  • 我修复了一些问题,我没有将 cmax 替换为 xmax_iterna.rm 在计算范围时会删除 NA。否则,你的范围将是(NA, NA),它会抛出一个错误。
  • 这会在f 的图表上绘制中点。我希望它们被绘制在xaxis
猜你喜欢
  • 2020-01-05
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
  • 2019-12-09
  • 1970-01-01
  • 2021-08-11
  • 2019-07-31
  • 1970-01-01
相关资源
最近更新 更多