为什么deparse(substitute(x))没有选择'x'的名字

rno*_*ian 2 evaluation arguments r function

我想知道为什么deparse(substitute(x))xlab不把名字中xxlab预期(见下图)?

gg <- function(x, xlab = deparse(substitute(x)), ylab = NA, freq = FALSE, ...) { 
    x <- round(x)
    ylab <- if(is.na(ylab) & freq) {
        "Frequency" 
    } else if(is.na(ylab) & !freq) {
        "Probability" 
    } else ylab
    z <- if(freq) table(x) else table(x)/length(x)
    plot(z, xlab = xlab, ylab = ylab, ...)
}

# Example of use:
gg(mtcars$gear)    # 'mtcars' is a base R built-in dataset
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Rol*_*and 6

原因是懒惰的评价.(请不要让我解释详细信息.它很复杂,您可以使用语言定义来研究它.但基本上,xxlab评估之前进行修改.)您可以使用以下方法轻松解决此问题force:

gg <- function(x, xlab = deparse(substitute(x)), ylab = NA, freq = FALSE, ...) {
  force(xlab)
  x <- round(x)
  ylab <- if(is.na(ylab) & freq) "Frequency" else if(is.na(ylab) & !freq) "Probability" else ylab
  z <- if(freq) table(x) else table(x)/length(x)
  plot(z, xlab = xlab, ylab = ylab, ...)
}
# Example of use:
gg(mtcars$gear)
Run Code Online (Sandbox Code Playgroud)

结果情节

  • 因为`force`只是`identity`的另一个名字,你*可以*只是把`xlab`放在函数的第一行.不过看起来很有趣,所以语法糖很好地说明为什么它是必要的. (2认同)