检查非标准评估 (NSE) 的快速方法是验证是否使用了某些关键字,例如substitute
,eval
等deparse
。请参阅下面的代码。它查看函数体并计算使用 NSE 相关关键字的次数。
is_nse <- function(x) {
nse_criteria <- c("substitute", "deparse", "eval", "parent.frame", "quote")
code <- as.character(body(x))
print(x)
cat("-------------------------------------------------------------------\n")
nse_count <- sapply(nse_criteria, function(x) sum(grepl(x, code)))
if(sum(nse_count) > 0)
warning("Possible non-standard evaluation")
nse_count
}
is_nse(as.Date.default)
输出:
function (x, ...)
{
if (inherits(x, "Date"))
x
else if (is.null(x))
.Date(numeric())
else if (is.logical(x) && all(is.na(x)))
.Date(as.numeric(x))
else stop(gettextf("do not know how to convert '%s' to class %s",
deparse1(substitute(x)), dQuote("Date")), domain = NA)
}
<bytecode: 0x0000021be90e8f18>
<environment: namespace:base>
-------------------------------------------------------------------
substitute deparse eval parent.frame quote
1 1 0 0 0
Warning message:
In is_nse(as.Date.default) : Possible non-standard evaluation