如何编写也需要字符输入的NES函数? [英] How to write an NES function that also takes character input?

查看:86
本文介绍了如何编写也需要字符输入的NES函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个R软件包,该软件包将字符串作为函数参数.现在,我想使用非标准评估以允许非字符串输入.另外,为了保持向后兼容性,我想保留函数采用字符串的可能性.

I´m working on a R package that takes strings as function arguments. Now I want to use non-standard evaluation to allow for non-string input. Also, to keep the backwards compatibility, I´d like to keep the possibility for the functions to take strings.

Hadley使用子集功能给出了示例并建议每个NES功能都应附有标准评估功能.

Hadley gives an example with the subset function and suggests that every NES function should be accompanied by a standard evaluation function.

library(lazyeval)
# standard evaluation
subset2_ <- function(df, condition) {
    r <- lazy_eval(condition, df)
    r <- r & !is.na(r)
    df[r, , drop = FALSE]
} 

subset2_(mtcars, lazy(mpg > 31))


# NES can be written easily afterwards

subset2 <- function(df, condition) {
    subset2_(df, lazy(condition))
}

虽然SE功能现在也接受带引号的输入,

While the SE function now also takes quoted input,

subset2_(mtcars, "mpg > 31")

NSE函数引发错误:

the NSE function throws an error:

subset2(mtcars, "mpg > 31")

但是我希望用户对带引号和不带引号的参数都具有相同的功能(NSE功能).

But I want the user to have the same function (the NSE function) for both quoted as well as unquoted arguments.

有什么想法吗?

推荐答案

NSE函数采用 NSE 输入.这就是这种模式的重点,不是吗?

The NSE function takes NSE input. That’s the point of this pattern, isn’t it?

subset2(mtcars, mpg > 31)

您当然可以允许NSE功能也接受字符输入,但是我强烈建议您不要这样做.不要混用SE和NSE,这没有任何优势,而且会造成混乱(由于您混用域,因此可能会引起错误).

You can of course allow the NSE function to take character input as well but I’d advise against this — strongly. Don’t mix SE and NSE, there’s no advantage to be had, and it sows confusion (and potentially bugs, since you’re mixing domains).

也就是说,以下当然可以工作:

That said, the following of course works:

subset2 <- function(df, condition) {
    if (is.character(substitute(condition)))
        subset2_(df, condition)
    else
        subset2_(df, lazy(condition))
}

如果出于向后兼容的原因,要允许NSE和SE使用相同的功能,建议您在以后的版本中逐步淘汰SE版本,并暂时添加弃用警告.要添加弃用警告:

If you want to allow NSE and SE in the same function for backwards compatibility reasons, I suggest phasing out the SE version in a future version, and adding a deprecation warning for now. To add the deprecation warning:

subset2 <- function(df, condition) {
    if (is.character(substitute(condition))) {
        msg = sprintf(paste0('Calling %s with a quoted expression is',
                             ' deprecated. Pass an unquoted expression',
                             ' instead, or use %s.'),
                      sQuote('subset2'), sQuote('subset2_'))
        .Deprecated(msg = msg)
        subset2_(df, condition)
    }
    else
        subset2_(df, lazy(condition))
}

这篇关于如何编写也需要字符输入的NES函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆