如何废弃一个参数?

11

在R语言中,是否有一种标准的弃用参数的方式?

例如:对于一个Web API包,我之前包含了一个paging=TRUE的参数,它将分页显示所有结果并下载全部内容。

现在我想要一个limit参数,只有当设置为limit=0时才下载全部内容。这有效地消除了paging参数的需求,因此我需要让用户知道它现在基本上不起作用了。我该怎么做?


1
你可以效仿lme4作者的做法。他们现在有三个参数可能会被弃用,因为他们一直在重命名一个参数:http://search.r-project.org/R/library/lme4/html/predict.merMod.html - Roland
3
为了更清晰明确,设置 limit = if(paging) 0 else theDefault 并在文档中说明不应使用 paging 参数。如果您对此感到强烈,还可以提供 warningmessage - Roland
2个回答

9

也许以下内容适合您?

foo <- function(paging = T, limit = 0) {
  if (!missing("paging"))
    warning("argument deprecated")
}

示例输出:

# > foo()
# > foo(limit = 0)
# > foo(T)
# Warning message:
#   In foo(T) : argument deprecated
# > foo(paging = T)
# Warning message:
#   In foo(paging = T) : argument deprecated

正如@Roland所指出的,该函数的文档应该明确提到该参数已被弃用。

2
不要使用 print 来输出消息。用户无法将其抑制。 - Roland

6

当我寻找解决方法以重命名包中函数的函数参数时,我发现了这个讨论。虽然这不是对你问题的确切答案,但我觉得可能对其他人也有帮助。

因此,为了重命名函数的参数而不破坏现有的函数调用,我基于@John Smith的答案提出了以下解决方案。

old_arg的功能仍适用于foo的弃用函数调用,并且对于新版本的foo函数调用,则忽略其作用。

# old version
foo <- function(x, y, old_arg = c("a", "b", "c")){

   old_arg <- match.arg(old_arg, c("a", "b", "c"))

   if(old_arg == "a"){
      return(x*y)
   }else if(old_arg == "b"){
      return(x+y)
   }else if(old_arg == "c"){
      return(x-y)
   }
}

# new version
foo <- function(x, y, new_arg = c("a", "b", "c"), old_arg = c("a", "b", "c")){

   if (!missing("old_arg")){
      warning("Argument deprecated, use new_arg instead. 
              The parameter new_arg is set equal the parameter old_arg.")
      new_arg <- old_arg
   }

   new_arg <- match.arg(new_arg, c("a", "b", "c"))
   if(new_arg == "a"){
      return(x*y)
   }else if(new_arg == "b"){
      return(x+y)
   }else if(new_arg == "c"){
      return(x-y)
   }
}

我认为这很有帮助。事实上,我最终做了类似的事情。我不会改变已接受的答案,因为那是一段时间以前的事了,但我认为人们会发现这个例子非常有用。 - jakub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接