带有变量名的 R missing() [英] R missing() with variable names

查看:21
本文介绍了带有变量名的 R missing()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 3.0.2 中,missing() 函数可以告诉我们是否缺少形式参数.

In R 3.0.2 the missing() function can tell us whether or not a formal parameter is missing.

如何避免硬编码传递给丢失的变量名?例如在

How can one avoid hardcoding the variable name passed into missing? e.g. in

demoargs <- function(a=3, b=2, d) {
    f <- formals(demoargs)  # Capture formal arguments
    formalNames <- names(f) # get variable names: a, b, d
    ...   
}

我希望能够在不以硬编码方式执行此操作的情况下检查缺少的形式,例如:

I would like to be able to check for missing formals without doing this in a hardcoded manner, e.g.:

missing(formalNames[1])  # returns invalid use of missing!

与 missing(d) 相反,目的是迭代以有限数量的方式处理的大量可选参数.我曾希望 get 或 as.name 能让我走上正轨,但似乎并非如此.

as opposed to missing(d) for the purpose of iterating over a large number of optional arguments that are handled in a limited number of manners. I had hoped that get or as.name my put me on the right track but this does not seem to be the case.

或者,我怀疑我可以使用 vararg 参数 (...) 来做到这一点,但是调用者能够通过检查函数声明来检查可接受的可选参数会很好.

Alternatively, I suspect that I could do this with the vararg arguments (...), but it would be nice for the caller to be able to inspect the acceptable optional arguments by examining the function declaration.

谢谢,玛丽

推荐答案

您可能首先尝试过类似 missing(as.name(formalNames[1]))missing(formalNames[1]) 并发现它们不起作用.

You probably first tried something like missing(as.name(formalNames[1])) or missing(formalNames[1]) and found that they do not work.

他们不这样做的原因是 missing() 是那些奇怪的函数之一——library()debug()是其他几个——它们将接受名称或名称的字符表示作为参数.在 missing(a)missing("a") 都将检查函数调用是否包含提供的参数 a;当您执行 missing(formalNames[1]) 并开始寻找名为 formalNames[1] 的不存在参数时,这不是很好.

The reason they don't is that missing() is one of those odd functions -- library() and debug() are a couple of others -- that will accept as an argument either a name or a character representation of a name. That's 'nice' in the sense that missing(a) and missing("a") will both check whether the function call included a supplied argument a; it's not so nice when you do missing(formalNames[1]) and it goes off to look for a non-existent argument named formalNames[1].

解决方案是使用do.call(),它在将第二个参数的元素传递给第一个参数中给出的函数之前评估它们.您可以这样做:

The solution is to use do.call(), which evaluates the elements of its second argument before passing them on to the function given in its first argument. Here's what you might do:

demoargs <- function(a=3, b=2, d) {
    formalNames <- names(formals()) # get variable names: a, b, d
    do.call(missing, list(formalNames[1]))
}

## Try it out
demoargs(a=42)
# [1] FALSE
demoargs()
# [1] TRUE

这篇关于带有变量名的 R missing()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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