在函数中设置条件(ifelse)参数 [英] Setting conditional(ifelse) arguments in a function

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

问题描述

我有一个简单的函数,在某种意义上,它的一个参数需要设为有条件的:

I have a simple function and one of its arguments needs to be made conditional, in the sense:

IFELSE NOT MISSING取给定值 如果不存在,则提供一些默认值 ELSE给出该参数的全局值

IFELSE NOT MISSING take the given value IFELSE NOT EXISTS then give some default value ELSE give the global value of that argument

类似这样的东西:

f <- function(x,y=ifelse(!missing("y"),y,ifelse(!exists("y"),1,get("y",envir=.GlobalEnv))))
{ 
  assign("y",y,envir=.GlobalEnv)
  return(x+y)
}

必需的输出:

#    :f(3) should give me 4 with global y=1
#    :f(4,2) should give me 6 with global y=2
#    :f(5) should give me 7 with global y=2
#Note that y does not exist when we first run the function

使用f(3)运行上述函数给我:-get("y",envir = .GlobalEnv)错误:找不到对象'y'

running the above function with f(3) gives me:- Error in get("y", envir = .GlobalEnv) : object 'y' not found

如果我在第一次使用中指定了y,则该函数运行正常,但是即使用户未在第一次使用中指定y参数,我也希望它能够运行

If i specify y in the first-go then the function works perfectly, but I want it to run even if the user doesnt specify the y argument in the first-go

有什么建议吗?

谢谢.

@Richard我认为如果函数或参数中缺少missing()并不重要,无论如何尝试使用此函数执行相同的操作:

@Richard i dont think it matters if missing() is in the function or in the argument, in any case try to do the same using this function:

f <- function(x,y)
{ 
  y=ifelse(!missing("y"),y,ifelse(!exists("y"),1,get("y",envir=.GlobalEnv)))
  assign("y",y,envir=.GlobalEnv)
  return(x+y)
}

推荐答案

首先,我将首先声明我不建议您这样做.您将不得不重新分配全局对象,这很危险,如果您需要返回并重新调用已被覆盖的值,可能会导致麻烦.

First, I'll begin by stating that I don't recommend you do this. You'll be messing around with reassignment of global objects, which can be dangerous and lead to trouble if you need to go back and recall a value that you've overwritten.

下一步,missing不应在函数的参数列表中使用.应该在函数主体中使用它来检查参数列表中的参数,并具有帮助文件中注明的特定用法.

Next, missing should not be used in the argument list of a function. It should be used in the function body to check the arguments in the argument list, and has specific usage that is noted in the help file.

也就是说,如果必须这样做,就可以了.

That said, if you must do it, here you go.

f <- function(x, y)
{
    if(missing(y)) {
        y <- if(exists("y", envir = .GlobalEnv)) {
            get("y", envir = .GlobalEnv)
        } else {
            1L
        }
    }
    assign("y", y, .GlobalEnv)
    x + y
}

> rm(y)
> f(3)
#[1] 4
> f(4, 2)
#[1] 6
> f(5)
#[1] 7

这篇关于在函数中设置条件(ifelse)参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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