18

我有一个 R 函数:

myFunc <- function(x, base='') {
}

我现在正在扩展函数,允许一组任意的额外参数:

myFunc <- function(x, base='', ...) {
}

如何禁用参数的部分参数匹配base我不能放...前面,base=''因为我想保持函数的向后兼容性(它通常被称为myFunction('somevalue', 'someothervalue')没有base明确命名)。

我被这样调用我的函数刺痛了:

myFunc(x, b='foo')

希望这意味着base='', b='foo',但 R 使用部分匹配并假设base='foo'

是否有一些代码我可以插入myFunc以确定传入的参数名称,并且只与参数的确切“基础”匹配base,否则将其分组为...?

4

6 回答 6

7

这是一个想法:

myFunc <- function(x, .BASE = '', ..., base = .BASE) {
    base
}

## Takes fully matching named arguments       
myFunc(x = "somevalue", base = "someothervalue")
# [1] "someothervalue"

## Positional matching works
myFunc("somevalue", "someothervalue")
# [1] "someothervalue"

## Partial matching _doesn't_ work, as desired
myFunc("somevalue", b="someothervalue")
# [1] ""
于 2013-03-07T07:24:09.033 回答
2

在@Hemmo 的提示下,刚刚以另一种方式解决了这个问题。

用于sys.call()了解如何myFunc调用(没有部分参数匹配,match.call用于此):

myFunc <- function(x, base='', ...) {
    x <- sys.call() # x[[1]] is myFunc, x[[2]] is x, ...
    argnames <- names(x)
    if (is.null(x$base)) {
        # if x[[3]] has no argname then it is the 'base' argument (positional)
        base <- ifelse(argnames[3] == '', x[[3]], '')
    }
    # (the rest of the `...` is also in x, perhaps I can filter it out by
    #  comparing argnames against names(formals(myFunc)) .

}
于 2013-03-08T00:28:39.270 回答
2

最简单的方法是简单地设置一些 R选项。尤其,

  • warnPartialMatchArgs: 合乎逻辑。如果为 true,则在参数匹配中使用部分匹配时发出警告。
  • warnPartialMatchAttr: 合乎逻辑。如果为 true,则在通过 attr 提取属性时是否使用部分匹配发出警告。
  • warnPartialMatchDollar: 合乎逻辑。如果为真,则警告如果部分匹配被 $ 用于提取。

设置这些变量现在会引发警告,如果你愿意,你可以变成错误。

于 2021-02-10T18:36:00.190 回答
0

这有点晚了。但为了将来参考,我有了这个想法。

使用带引号的名称可以避免部分匹配。在函数中,对参数使用 sys.call()。

    > myFunc <- function(x, base="base", ...) {
+     ## get the arguments
+     ss=sys.call()
+     
+     ## positional arguments can be retrieved using numbers
+     print(paste("ss[[2]]=",ss[[2]]))
+     
+     ## named arguments, no partial matching
+     print(ss[['base']]) ## NULL
+     
+     ## named arguments, no partial matching
+     print(ss[['b']]) ## "a"
+     
+     ## regular call, partially matched
+     print(base) ## "a"
+     
+     ## because 'b' is matched to 'base', 
+     ## 'b' does not exist, cause an error
+     print(b)
+ }
> 
> myFunc(x=1,b='a')
[1] "ss[[2]]= 1"
NULL
[1] "a"
[1] "a"
Error in print(b) : object 'b' not found
> myFunc(1,base="b")
[1] "ss[[2]]= 1"
[1] "b"
NULL
[1] "b"
Error in print(b) : object 'b' not found
> myFunc(2,"c")
[1] "ss[[2]]= 2"
NULL
NULL
[1] "c"
Error in print(b) : object 'b' not found
> 
于 2017-03-17T04:39:23.240 回答
0

可以用来sys.call()访问调用者给出的函数参数。必须小心,因为sys.call()不会评估参数,而是为您提供调用的表达式。当函数...作为参数调用时,这变得特别困难:sys.call()将只包含...,而不是它们的值。但是,可以将sys.call()和评估它作为另一个函数的参数列表,例如list()。这会评估所有承诺并丢弃一些信息,但是当我试图规避 R 的内部匹配时,我看不出如何解决这个问题。

一种想法是模拟严格匹配。我附加了一个辅助函数,如果将其作为函数中的第一个命令调用,它就可以做到这一点:

fun = function(x, base='', ...) {
  strictify()  # make matching strict

  list(x, base, ...)
}

这会过滤掉不匹配的参数:

> fun(10, b = 20)                                                                                                                                                                                   
[[1]]                                                                                                                                                                                               
[1] 10

[[2]]
[1] ""

$b
[1] 20

并且也应该在大多数其他情况下工作(有或没有..., 右边...有参数 , 有参数默认值)。它唯一不适用的是非标准评估,例如,当尝试使用substitute(arg).

辅助函数

strictify <- function() {
  # remove argument values from the function
  # since matching already happened
  parenv <- parent.frame()  # environment of the calling function
  rm(list=ls(parenv), envir=parenv)  # clear that environment

  # get the arguments
  scall <- sys.call(-1)  # 'call' of the calling function
  callingfun <- scall[[1]]
  scall[[1]] <- quote(`list`)
  args <- eval.parent(scall, 2)  # 'args' is now a list with all arguments

  # if none of the argument are named, we need to set the
  # names() of args explicitly
  if (is.null(names(args))) {
    names(args) <- rep("", length(args))
  }

  # get the function header ('formals') of the calling function
  callfun.object <- eval.parent(callingfun, 2)
  callfun.header <- formals(callfun.object)
  # create a dummy function that just gives us a link to its environment.
  # We will use this environment to access the parameter values. We
  # are not using the parameter values directly, since the default
  # parameter evaluation of R is pretty complicated.
  # (Consider fun <- function(x=y, y=x) { x } -- fun(x=3) and
  # fun(y=3) both return 3)
  dummyfun <- call("function", callfun.header, quote(environment()))
  dummyfun <- eval(dummyfun, envir=environment(callfun.object))
  parnames <- names(callfun.header)

  # Sort out the parameters that didn't match anything
  argsplit <- split(args, names(args) %in% c("", parnames))
  matching.args <- c(list(), argsplit$`TRUE`)
  nonmatching.arg.names <- names(argsplit$`FALSE`)

  # collect all arguments that match something (or are just
  # positional) into 'parenv'. If this includes '...', it will
  # be overwritten later.
  source.env <- do.call(dummyfun, matching.args)
  for (varname in ls(source.env, all.names=TRUE)) {
    parenv[[varname]] <- source.env[[varname]]
  }

  if (!"..." %in% parnames) {
    # Check if some parameters did not match. It is possible to get
    # here if an argument only partially matches.
    if (length(nonmatching.arg.names)) {
      stop(sprintf("Nonmatching arguments: %s",
          paste(nonmatching.arg.names, collapse=", ")))
    }
  } else {
    # we manually collect all arguments that fall into '...'. This is
    # not trivial. First we look how many arguments before the '...'
    # were not matched by a named argument:
    open.args <- setdiff(parnames, names(args))
    taken.unnamed.args <- min(which(open.args == "...")) - 1
    # We throw all parameters that are unmatched into the '...', but we
    # remove the first `taken.unnamed.args` from this, since they go on
    # filling the unmatched parameters before the '...'.
    unmatched <- args[!names(args) %in% parnames]
    unmatched[which(names(unmatched) == "")[seq_len(taken.unnamed.args)]] <- NULL
    # we can just copy the '...' from a dummy environment that we create
    # here.
    dotsenv <- do.call(function(...) environment(), unmatched)
    parenv[["..."]] <- dotsenv[["..."]]
  }
}

也可以有一个将正常匹配函数转换为严格匹配函数的函数,例如

strict.fun = strictificate(fun)

但这将使用相同的技巧。

于 2017-12-05T17:11:56.037 回答
-2

这是一个令人作呕的可怕黑客,但它可能会完成工作:

myFunc <- function(x, base='', b=NULL, ba=NULL, bas=NULL, ...) {
  dots <- list(b=b, ba=ba, bas=bas, ...)
  #..
}
于 2013-03-07T07:25:30.503 回答