当内部函数参数依赖于可选参数时,参数传入R.

时间:2022-01-25 11:00:24

I'm working in R and need to pass arguments to a function so that they can be used as arguments when calling another function within the original. In the example below you can see that I'm interested in calling interiorFunc() every time primaryFunc() is called but the value of the first parameter is dependent on the existence of a second parameter. If I declare 'parameter 2' then I want a different set of arguments than if I don't declare 'parameter 2' in the function call. Here is the definition for the interior function:

我在R中工作,需要将参数传递给函数,以便在调用原始函数中的其他函数时可以将它们用作参数。在下面的示例中,您可以看到我每次调用primaryFunc()时都对调用interiorFunc()感兴趣,但第一个参数的值取决于是否存在第二个参数。如果我声明'参数2',那么我想要一个不同的参数集,而不是在函数调用中没有声明'参数2'。这是内部功能的定义:

interiorFunc(data, resp, param1, param2)
{
  if(missing(param2)) 
  { 
    print(paste("Do analysis without parameter 2 on dataset of size",nrow(data),"with response",resp)
  }else{
    print(paste("Do analysis with parameter 2 on dataset of size",nrow(data),"with response",resp))
  }

}

And here is the function that calls it:

以下是调用它的函数:

primaryFunc <- function(dataset, ...)
{
  if(parameter 2 has been declared in the call to primaryFunc)
  {
    results <- interiorFunc(dataset, ...)
  }else{
    modifedData <- sample(dataset, 2*dataset, replace = TRUE)
    results <- interiorFunc(modifiedData, ...)
  }

  return(results)
}

The function call would either be:

函数调用可以是:

interiorFuncResults <- primaryFunc(dataset, response, parameter1)

or

要么

interiorFuncResults <- primaryFunc(dataset, response, parameter1, parameter2)

so I need to determine prior to calling the interior function if it's 'parameter2' value has been passed in. Here is a definition of interiorFunc() to make this example reproducible:

所以我需要在调用内部函数之前确定它是否传入了'parameter2'值。这里有一个interiorFunc()的定义,使这个例子可以重现:

Thank you for your help.

感谢您的帮助。

1 个解决方案

#1


2  

I think one of the common strategies is to filter the names,

我认为其中一个常见策略是过滤名称,

sub <- function(x, y, param=NULL, ...){
  if(!is.null(param))
    message(param, "is being used") else
      message("not seeing it")
}

main <- function(a=1, b=2, ..., c=3){

  dots <- list(...)

  if("param" %in% names(dots))
    sub(a, b, ...) else
      sub(a, b, ...)

}

main(z=2)

main(param = 2)

which, of course, assumes that ... only will receive fully named arguments.

当然,这假设......只会收到完全命名的参数。

#1


2  

I think one of the common strategies is to filter the names,

我认为其中一个常见策略是过滤名称,

sub <- function(x, y, param=NULL, ...){
  if(!is.null(param))
    message(param, "is being used") else
      message("not seeing it")
}

main <- function(a=1, b=2, ..., c=3){

  dots <- list(...)

  if("param" %in% names(dots))
    sub(a, b, ...) else
      sub(a, b, ...)

}

main(z=2)

main(param = 2)

which, of course, assumes that ... only will receive fully named arguments.

当然,这假设......只会收到完全命名的参数。