【问题标题】:match.arg function for list argument列表参数的 match.arg 函数
【发布时间】:2012-12-28 03:44:28
【问题描述】:

我的问题很简单。

x=list(type="call")

FUN <- function(x=list(type=c("call","put")))
{
  x$type=match.arg(x$type)
}

这会返回一个错误:

> FUN(x)
Error in match.arg(x$type) : 'arg' should be one of “”

有什么想法吗?

【问题讨论】:

  • 我不认为这是可能的;来自?match.arg的默认函数参数用于匹配输入,但这里您的默认值不是简单的字符向量。
  • 在重新打开之前,这是一个丑陋的解决方法,FUN = function(x=list(type=c("call","put"))){match.arg(x$type, formals(FUN)[['x']][['type']]) } ; FUN(x=list(type='call'))
  • @这是一个真正的 R 问题吗
  • @baptiste 注意到“不起作用”通常是 NARQ 会有所帮助。如果你觉得你知道它为什么不起作用,它会帮助edit 并添加该信息。我已重新打开,因此您可以添加解决方法。

标签: r arguments match


【解决方案1】:

也许这就是你想要的:

FUN <- function(x=list(type=c("call","put")))
{
  x$type=match.arg(x$type, c('call', 'put'))
}


> print(FUN())
[1] "call"
> print(FUN(x))
[1] "call"
> print(FUN(list(type="put")))
[1] "put"

【讨论】:

  • 谢谢。这正是我想要的!
  • 直到现在我还在使用 pmatch("med", c("mean", "median", "mode"))。但你的最后一个建议是我见过的最好的。
猜你喜欢
  • 1970-01-01
  • 2023-01-22
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
相关资源
最近更新 更多