测试函数的参数是否在 R 中设置 [英] Test if an argument of a function is set or not in R

查看:30
本文介绍了测试函数的参数是否在 R 中设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 f 有两个参数(p1p2):

I have a function f that takes two parameters (p1 and p2):

如果参数 p2 没有值传递给函数,则应使用 p1^2 的值代替.但是我怎样才能在函数中找出一个值是否给定.问题是如果没有值,变量 p2 不会被初始化.因此我无法测试 p2 是否为 NULL.

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
}

是否可以以某种方式检查 p2 的值是否已传递给函数?(我找不到 isset() - 函数或类似的东西.)

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

推荐答案

您可以使用 missing() 函数.

f <- function(p1, p2) {
    if(missing(p2)) {
        p2=p1^2
    }
    p1-p2
}

或者,您可以将 p2 的值默认设置为 NULL.我有时更喜欢这种解决方案,因为它允许将参数传递给嵌套函数.

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

您也可以使用 missing() 在技术上做到这一点,但是您必须在 f.wrapper 中包含一个 missing() 语句 也是.

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屋!

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