如何在R中使用`...`定义用户功能?

时间:2018-11-07 08:25:08

标签: r function nested arguments user-defined-functions

在R文档中,它说明了

  

参数'...'可用于允许一个函数将参数设置传递给另一函数。

我不太确定它是如何工作的……在我的想象中,它将像这样工作:

$canNAMES = ["name 1","name 2","name 3"];

$data = json_decode ('[
{
    "agency": "test agency",
    "work_end": "21-Oct",
    "contractor": "name 3",
    "rate": "£30.00",
    "hours": 32,
    "exp": null,
    "net": "£960.00",
    "vat": "£192.00",
    "gross": "£1,152.00"
},
{
    "agency": "test agency",
    "work_end": "21-Oct",
    "contractor": "name 1",
    "rate": "£25.00",
    "hours": 30,
    "exp": null,
    "net": "£750.00",
    "vat": "£150.00",
    "gross": "£900.00"
}
]');

foreach ( $canNAMES as $name )  {
    foreach ( $data as $entry ) {
        if ( $name == $entry->contractor )    {
            print_r($entry);
        }
    }
}

发生的事情是:

Arithmetic <- function(x, ...) {
  calculate <- function(x, y = 1, operand = "add") {
    if (operand == "add") {return(x + y)}
    if (operand == "subtract") {return(x - y)}
    if (operand == "multiply") {return(x * y)}
    if (operand == "devide") {return(x / y)}
  }
  return(calculate(x, y, operand))
}
Arithmetic(x = 3, y = 4, operand = "subtract")
## [1] -1

Error in calculate(x, y, operand) : object 'operand' not found 对R中用户定义函数的确切作用是什么?

1 个答案:

答案 0 :(得分:0)

这就足够了:

calculate <- function(x, y, operand = "add") {
  if (operand == "add") {return(x + y)}
  if (operand == "subtract") {return(x - y)}
  if (operand == "multiply") {return(x * y)}
  if (operand == "devide") {return(x / y)}
}

输出:

calculate(3, 4, "subtract")
[1] -1

此功能默认具有“添加” operand,但是您可以将其更改为所需的任何内容。

基本上,如果您已经定义了参数,则不需要...

如果您想包含...,则可以从以下内容开始:

calculate <- function(x, ...) {

  args_list <- list(...)

  if (args_list[[2]] == "add") {return(x + args_list[[1]])}
  if (args_list[[2]] == "subtract") {return(x - args_list[[1]])}
  if (args_list[[2]] == "multiply") {return(x * args_list[[1]])}
  if (args_list[[2]] == "devide") {return(x / args_list[[1]])}

}

calculate(3, 4, "subtract")
[1] -1