简体   繁体   English

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

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

I was wondering why deparse(substitute(x)) for my xlab does not put the name of x for xlab as expected ( see picture below )? 我想知道为什么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

在此处输入图片说明

The reason is lazy evaluation. 原因是懒惰的评估。 (Don't ask me to explain the details, please. It's complicated and you can study this with the language definition . But basically, x is modified before xlab is evaluated.) You can fix this easily by using force : (请不要让我解释细节。它很复杂,您可以使用语言定义进行研究 。但是基本上,在对xlab进行评估之前已对x进行了修改。)您可以使用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)

结果图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM