测试一个函数的参数是否设置在R中 [英] Test if an argument of a function is set or not in R
问题描述
我有一个函数 如果参数 是否有可能检查某个值为 您使用 或者,您可以将p2的值默认设置为NULL。我有时更喜欢这个解决方案,因为它允许将参数传递给嵌套的函数。 编辑:你可以在技术上用 f
,它有两个参数( p1
和 p2 <
以及。
$ b $ p p2
没有值传递给函数,那么值应该使用 p1
^ 2来代替。但是如何在函数中找到值,如果给出值或不。问题是,如果没有值,变量 p2
不会被初始化。因此,我无法测试 p2
是 NULL
。
< pre $ f < - 函数(p1,p2){
if(is.null(p2)){
p2 = p1 ^ 2
}
p1-p2
}
p2
传递给函数还是不行? (我无法找到 isset()
- 函数或类似的东西。)
missing()
这个函数。
f < - 函数(p1,p2){
if(missing(p2)){
p2 = p1 ^ 2
}
p1-p2
}
$ $ p $ f < - 函数(p1,p2 = NULL){
if(is.null(p2)){
p2 = p1 ^ 2
}
p1-p2
}
f.wrapper< -function(p1,p2 = NULL){
p1 <-2 * p1
f(p1,p2)
}
> f.wrapper(1)
[1] -2
> f.wrapper(1,3)
[1] -1
missing()
来做到这一点,但是你必须包含一个 missing()
code> f.wrapper
I have a function f
that takes two parameters (p1
and p2
):
If for the parameter p2
no value was passed to the function, the value of p1
^2 should be used instead. But how can I find out within the function, if a value is given or not. The problem is that the variable p2
is not initialized if there was no value. Thus I can't test for p2
being NULL
.
f <- function(p1, p2) {
if(is.null(p2)) {
p2=p1^2
}
p1-p2
}
Is it somehow possible to check if a value for p2
was passed to the function or not? (I could not find an isset()
- function or similar things.)
You use the function missing()
for that.
f <- function(p1, p2) {
if(missing(p2)) {
p2=p1^2
}
p1-p2
}
Alternatively, you can set the value of p2 to NULL by default. I sometimes prefer that solution, as it allows for passing arguments to nested functions.
f <- function(p1, p2=NULL) {
if(is.null(p2)) {
p2=p1^2
}
p1-p2
}
f.wrapper <-function(p1,p2=NULL){
p1 <- 2*p1
f(p1,p2)
}
> f.wrapper(1)
[1] -2
> f.wrapper(1,3)
[1] -1
EDIT: you could do this technically with missing()
as well, but then you would have to include a missing()
statement in f.wrapper
as well.
这篇关于测试一个函数的参数是否设置在R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!