④短缺()与变量名 [英] R missing() with variable names

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

问题描述

在R里面3.0.2失踪()函数可以告诉我们一个正式的参数是否丢失。

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
    ...   
}

我想能够检查缺失的形参而不硬codeD的方式这样做的,例如:

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!

而不是失踪(d)就遍历了大量的在举止有限数量的处理可选参数的目的。我曾希望得到或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.

此外,我怀疑是我能与可变参数的参数(...)做到这一点,但是这将是很好的主叫方能够通过检查函数声明视察接受可选参数。

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.

谢谢,
玛丽

推荐答案

您可能第一次尝试类似缺失(as.name(formalNames [1]))缺失(formalNames [1]),发现他们不工作。

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

他们不这样做的原因是,失踪()是那些奇怪的功能之一 - 库()调试()一对夫妇他人 - 这将接受作为参数或者名称或名称的字符重新presentation。这就是好在这个意义上,缺失(一)缺失(A)都将检查是否函数调用包含一个提供的参数 A ;当你做的不是很好缺失(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

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

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