S4泛型中的可选参数 [英] Optional arguments in S4 generics

查看:186
本文介绍了S4泛型中的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dbGetQuery RMongo 。它被声明为

dbGetQuery is an S4 generic in RMongo. It is declared as

dbGetQuery(rmongo.object, collection, query, skip=0, limit=1000)

在R中有这样的函数, skip limit 是可选参数。然而,当我以这种方式调用它时,

With a function like this in R, skip and limit are optional arguments. However, when I call it in this way

dbGetQuery(mongo, 'changesPerTypeEpoch', '{}', limit=10000)

我得到一个错误:

I get an error:

$ (函数(类,fdef,mtable)中的错误:

无法为函数'dbGetQuery'找到用于签名''RMongo','字符','字符'的继承方法,missing,numeric'

Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘dbGetQuery’ for signature ‘"RMongo", "character", "character", "missing", "numeric"’

查看源代码,我发现为通用定义了两个签名: / p>

Looking at the source code, I found there are two signatures defined for the generic:

signature(rmongo.object="RMongo", collection="character", query="character", skip='numeric', limit='numeric')
signature(rmongo.object="RMongo", collection="character", query="character", skip='missing', limit='missing')

所以为了使它不需要传递 skip ,它需要有另一个签名:

So in order to make it work without passing skip, it needs to have another signature:

signature(rmongo.object="RMongo", collection="character", query="character", skip='missing', limit='numeric')

然而,这让我感到不舒服,因为为了在S4泛型中创建 n 可选参数,必须定义2 ^ n个签名。有没有更好的方法来定义S4泛型中的可选参数?

However, that makes me feel uncomfortable, because in order to make n optional arguments in a S4 generic, one has to define 2^n signatures. Is there any better way to define optional arguments in S4 generic?

推荐答案

泛型可以限制实际调度的参数数量发生(使用setGeneric的'signature'参数)(例如,'skip'和'limit'永远不会是数字以外的任何东西,所以不应该包含在dispatch中。可选参数出现在'..'之后并不罕见。 '(它们需要拼写完整,而不是按位置进行匹配,但显式看起来像是一个好主意;'...'需要允许方法公开自己的附加参数)。 b
$ b

A generic can limit the number of arguments on which dispatch actually occurs (using the 'signature' argument to setGeneric) (e.g., 'skip' and 'limit' will never be anything other than a numeric, so should not be included in dispatch. It's not unusual for optional arguments to appear after '...' (they need to be spelled in full, instead of being matched by position, but being explicit seems like a good idea here; '...' are needed to allow methods to expose their own additional arguments)

setGeneric("fancy",
    function(x, y, ..., z=1, verbose=TRUE) standardGeneric("fancy"),
    signature=c("x", "y"))

人们也可以为类ANY编写方法,虽然这是一个非常有信心的承诺。也许对于RMongo来说,使用DBI包中的泛型会更好。

One can also write methods for class 'ANY', although that's a pretty confident promise. Probably it would be better for RMongo to use the generics from the DBI package.

这篇关于S4泛型中的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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