【问题标题】:How to define user function with `...` in R? [duplicate]如何在R中用`...`定义用户函数? [复制]
【发布时间】:2019-04-10 15:54:01
【问题描述】:

在 R 文档中,它解释说

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

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

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 中用于用户定义的函数的?

【问题讨论】:

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


【解决方案1】:

这就够了:

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

【讨论】:

  • 您在指定函数时是对的,但问题集中在“...”参数的逻辑和使用上。
  • @Tomas 是的,但在这个特定的功能中,我看不到“...”的目的。如果问题只是关于它的使用,那么在 Stack 的其他地方已经有几个答案了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
相关资源
最近更新 更多