[英]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
不投入名称x
为xlab
预期( 见下图 )?
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.