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

why deparse(substitute(x)) not picking the name of 'x'

我想知道为什么我的 xlabdeparse(substitute(x)) 没有按预期为 xlab 放置 x 的名称(见下图)?

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

原因是懒惰求值。 (请不要让我解释细节。这很复杂,你可以用 language definition 研究这个。但基本上, 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)