R 将match.call()与mapply一起使用

R 将match.call()与mapply一起使用,r,mapply,R,Mapply,我有一个函数,它基本上将布尔条件作为参数的字符串输出(函数的细节在这里并不重要) 我是这样得到的: combinations = expand.grid(Sex=c("NA", "male", "female"), SmokingHx=c("NA", "current", "former", "never"), conjunction=c("&", "|"),

我有一个函数,它基本上将布尔条件作为参数的字符串输出(函数的细节在这里并不重要)

我是这样得到的:

combinations = expand.grid(Sex=c("NA", "male", "female"), 
                           SmokingHx=c("NA", "current", "former", "never"), 
                           conjunction=c("&", "|"),
                           stringsAsFactors=FALSE)
我用
mapply
调用
makeClause

mapply(makeClause, Sex=combinations$Sex,SmokingHx=combinations$SmokingHx, conjunction=combinations$conjunction)
查看
arglist
变量,我得到:

$Sex
dots[[1L]][[1L]]

$SmokingHx
dots[[2L]][[1L]]

$conjunction
dots[[4L]][[1L]]
如果我调用
as.list(environment())
而不是
as.list(match.call())
我会得到:

$Sex
[1] "male"

$SmokingHx
[1] "NA"

$conjunction
dots[[4L]][[1L]] # notice this is the only one for which I don't get the actual string
所以我有两个问题:

  • 您能解释一下导致将其作为参数值而不是实际字符串值获取的R内部结构吗
  • 我如何纠正这一点,即获取参数列表中的字符串值
  • 谢谢

    为什么会发生这种情况:
    match.call
    将引用的调用捕获为语言对象。
    dots
    业务是
    mapply
    用来调用函数的,因此
    match.call的返回值是正确的。它只是匹配为您的函数构造的
    mapply
    调用,并返回引用的(即未计算的)值。内部
    mapply
    正在做类似的事情(虽然不是真的,因为它是内部C代码):

    如果您想要获取函数的所有参数而不必知道它们的名称,可以执行以下操作:

    mget(names(formals()))
    
    尝试(为了清晰起见简化趣味性):


    请制作样品。包括我们可以测试的最小数据集。显示您实际如何调用
    mapply()
    。已编辑,很抱歉,我无法在本示例中使用“$conjunction”重现您的错误。is有一个“[4L]”的事实让我觉得有些地方“连接词”拼写错误,或者有些地方有一个额外的逗号。你的函数真的需要命名参数吗?如果没有,并且您只想为所有这些函数做一些事情,那么只做
    makeClause@MrFlick怎么样,但是这样做会丢失参数匹配和潜在的重新排序。
    
    $Sex
    [1] "male"
    
    $SmokingHx
    [1] "NA"
    
    $conjunction
    dots[[4L]][[1L]] # notice this is the only one for which I don't get the actual string
    
    dots <- list(...)
    call <- list()
    for(j in seq_along(dots[[1]])) {
      for(i in seq_along(dots)) call[[i]] <- bquote(dots[[.(j)]][[.(i)]])
      eval(as.call(c(quote(FUN), call))))
    }
    
    list(Sex, SmokingHx, conjunction)
    
    mget(names(formals()))
    
    makeClause <-function(Sex, SmokingHx, conjunction) mget(names(formals()))
    
    with(combinations, t(mapply(makeClause, Sex, SmokingHx, conjunction)))
    
           Sex      SmokingHx conjunction
    NA     "NA"     "NA"      "&"        
    male   "male"   "NA"      "&"        
    female "female" "NA"      "&"        
    NA     "NA"     "current" "&"        
    male   "male"   "current" "&"        
    female "female" "current" "&"      
    ... further rows omitted