嵌套函数中的省略号扩展:错误“...3 在不正确的上下文中使用,没有...查看" [英] Ellipsis expansion in nested functions: Error "..3 used in an incorrect context, no ... to look in"

查看:33
本文介绍了嵌套函数中的省略号扩展:错误“...3 在不正确的上下文中使用,没有...查看"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码片段:

require(lattice)
f.barchart <- function(...) {
    barchart(...,
        panel = function(x, y, ...) {
            panel.barchart(x, y, ...)
        }
    )
}

x <- data.frame(a = c(1,1,2,2), b = c(1,2,3,4), c = c(1,2,2,1))
f.barchart(a ~ b, data = x, groups = c)

导致抛出以下错误:

..3 used in an incorrect context, no ... to look in

当我使用以下定义时:

f.barchart <- function(...) {
    substitute(barchart(...,
        panel = function(x, y, ...) {
            panel.barchart(x, y, ...)
        }
    ))
}

我明白了:

barchart(a ~ b, data = x, groups = c,
    panel = function(x, y, ...) {
        panel.barchart(x, y, a ~ b, data = x, groups = c)
    })

我不确定这是否是上述错误的原因,但这意味着panel.barchart 中的省略号被错误地扩展为提供给 f.barchart 而不是面板的参数的内容功能.

I'm not sure if this is the cause of above error but this would mean that the ellipsis in panel.barchart gets wrongly expanded with the contents of the arguments given to f.barchart and not the panel function.

有没有办法避免这个问题?我怎样才能做这个功能工作?

Is there a way to avoid this problem? How can I make the function work?

推荐答案

据我所知,这不是因为嵌套的 ... 而是因为条形图中的第一个 ....所以即使这样也行不通:

As far as I understand, this happens not because of the nested ... but because of the first ... in barchart. So even this does not work:

f.barchart <- function(...) {
    barchart(...)
}

x <- data.frame(a = c(1,1,2,2), b = c(1,2,3,4), d = c(1,2,2,1))
print(f.barchart(a ~ b, data = x, groups = d))

我认为这是因为 ... 是一个配对列表,而 barchart 需要单独的参数.我们需要解压缩对列表,同时确保我们不会过早评估它.以下是我的解决方案:

I think this is because ... is a pairlist while barchart is expecting individual arguments. We need to unpack the pairlist, while making sure that we do not evaluate it too soon. The following is my solution:

f.barchart <- function(...) {
  cl<-match.call()
  cl$panel=function(x, y, ...) {
            panel.barchart(x, y, ...)
          }
  cl[[1]]=barchart
  eval(cl)
}

我们使用 match.call 捕获对 f.barchart 的调用,它扩展了点,将面板参数添加到调用中,将要调用的函数设置为 barchart,然后评估调用.就像我们添加面板参数一样,我们可以删除 f.barchart 使用但不需要传递给 barchart 的参数.

We capture the call to f.barchart using match.call which expands the dots, add the panel argument to the call, set the function to be called to barchart and then evaluate the call. Just as we added the panel argument, we could delete arguments which are used by f.barchart but which do not need to be passed to barchart.

这篇关于嵌套函数中的省略号扩展:错误“...3 在不正确的上下文中使用,没有...查看"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆