【问题标题】:why deparse(substitute(x)) not picking the name of 'x'为什么 deparse(substitute(x)) 不选择“x”的名称
【发布时间】:2018-06-05 14:54:06
【问题描述】:

我想知道为什么我的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

【问题讨论】:

    标签: r function arguments evaluation


    【解决方案1】:

    原因是懒惰的评估。 (请不要让我解释细节。它很复杂,你可以用language definition研究这个。但基本上,x是在评估xlab之前修改的。)你可以使用@轻松解决这个问题987654326@:

    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)
    

    【讨论】:

    • 另外,我认为可能更常见的模式是默认使用xlab = NULL,然后让函数的第一行检查它是否为空,如果是,则执行deparse(substitute())到那时。
    • @joran 或不使用默认值并将if(missing(xlab)) xlab &lt;- ... 作为第一行,
    • 由于force 只是identity 的另一个名称,您可以xlab 放在函数的第一行。不过,它看起来很有趣,所以语法糖很好地说明了为什么它是必要的。
    猜你喜欢
    • 2013-09-01
    • 2021-04-10
    • 2022-01-12
    • 1970-01-01
    • 2015-06-16
    • 2014-11-12
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多