【问题标题】:How does the curve function in R work? - Example of curve functionR中的曲线函数如何工作? - 曲线函数示例
【发布时间】:2015-03-01 15:25:27
【问题描述】:

以下代码如何工作?我在阅读 R ?curve 的帮助行时得到了这个例子。但是这个我没看懂。

  for(ll in c("", "x", "y", "xy"))
     curve(log(1+x), 1, 100, log = ll,
        sub = paste("log= '", ll, "'", sep = ""))

特别是,我习惯于将数值作为for-loop 中的参数作为,

  for(ll in 1:10)

但是下面的命令是什么意思:

  for(ll in c("","x","y","xy"))

c("","x","y","xy") 看起来像一个字符串向量? c("","x","y","xy") 如何在 curve 内部工作 作为log(1+x)[这里的x是什么?字符串“x”?在c("","x","y","xy")] 和log=ll 中?

【问题讨论】:

  • 曲线中的log(1+x) 部分不受循环的直接影响。如您所见,ll 遍历字符向量c("","x","y","xy") 并提供给curve 内的log 参数。参数说明为:The value of log is used both to specify the plot axes (unless add = TRUE) and how ‘equally spaced’ is interpreted: if the x component indicates log-scaling, the points at which the expression or function is plotted are equally spaced on log scale. 所以如果你定义比如log = "x" 表示你的x轴将以对数显示。
  • 简短的回答是参数ll 仅被传递给curve 中的形式参数,即“期望”(或更准确地定义为接收)字符值。
  • for (letter in c("a", "b", "c")) print(letter)

标签: r plot arguments curve


【解决方案1】:

显然,关于 R 中 curve 函数的工作原理,尤其是关于 log 参数的堆栈溢出问题没有答案,所以这可能是一个深入研究它的好机会(顺便说一句,我喜欢这个问题):

首先是简单的部分:

c("","x","y","xy") 是一个字符串向量或更正式的字符向量。

for(ll in c("","x","y","xy")) 将开始一个 4 次迭代的循环,每次 ll 将分别为 '','x','y','xy'。不幸的是,这个例子的构建方式你只会看到最后一个为ll = 'xy'绘制的。

让我们深入到curve函数的源代码来回答剩下的问题:

  • 首先xlog(1+x) 中代表什么?

log(1+x) 是一个函数。 x 表示在以下部分的curve 函数内创建的数字向量(来自源代码):

 x <- exp(seq.int(log(from), log(to), length.out = n)) #if the log argument is 'x' or
 x <- seq.int(from, to, length.out = n)               #if the log argument is not 'x' 
 #in  our case from and to are 1 and 100 respectively 

只要 n 参数是默认值,x 向量将包含 101 个元素。显然log(1+x) 中的xlog 参数中的'x' 完全不同。

至于y,它总是被创建为(来自源代码):

 y <- eval(expr, envir = ll, enclos = parent.frame()) #where expr is in this case log(1+x), the others are not important to analyse now.
 #i.e. you get a y value for each x value on the x vector which was calculated just previously
  • 其次,log 参数的目的是什么?

log 参数决定将记录 xy 轴中的哪一个。 x 轴如果'x'log 参数,y 轴如果'y'log 参数,两个轴如果'xy'log 参数,如果@987654352 没有对数刻度@ 参数是''

这里需要提一下,在curve函数中的plot函数中计算x轴或y轴的log,即curve函数只是plot的封装功能。

上面说了这就是为什么如果log 参数是'x'(见上文)向量x 的日志值的指数被计算出来,以便它们将返回到plot 内的日志值功能。

附: curve函数的源代码可以在控制台输入graphics::curve查看。

我希望这现在有点意义!

【讨论】:

  • @docendodiscimus 非常感谢 :) !
猜你喜欢
  • 2012-02-21
  • 2022-11-15
  • 2021-07-05
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 2018-04-03
  • 1970-01-01
相关资源
最近更新 更多