如何查看 S4 函数的定义?例如,我想在包 TSdbi 中查看 TSconnect 的定义。命令
showMethods("TSconnect")
揭示了除其他外,还有一个用于 drv="histQuoteDriver"、dbname="character"的函数。
我怎样才能看到这个函数的定义?如果它是 S3 函数,则只有第一个可定义参数 (drv),可以使用 print(TSconnect.histQuoteDriver) 检查。
编辑 :从 r-forge 我找到了所需的输出:
setMethod("TSconnect", signature(drv="histQuoteDriver", dbname="character"),
definition= function(drv, dbname, user="", password="", host="", ...){
# user / password / host for future consideration
if (is.null(dbname)) stop("dbname must be specified")
if (dbname == "yahoo") {
con <- try(url("http://quote.yahoo.com"), silent = TRUE)
if(inherits(con, "try-error"))
stop("Could not establish TShistQuoteConnection to ", dbname)
close(con)
}
else if (dbname == "oanda") {
con <- try(url("http://www.oanda.com"), silent = TRUE)
if(inherits(con, "try-error"))
stop("Could not establish TShistQuoteConnection to ", dbname)
close(con)
}
else
warning(dbname, "not recognized. Connection assumed working, but not tested.")
new("TShistQuoteConnection", drv="histQuote", dbname=dbname, hasVintages=FALSE, hasPanels=FALSE,
user = user, password = password, host = host )
} )
有没有办法从 R session 中获得这个定义?
最佳答案
S4类比较复杂,建议reading this introduction .
在这种情况下,TSdbi 是一个通用 S4 类的示例,它被所有特定数据库包(例如 TSMySQL、TSPostgreSQL 等)扩展。 TSdbi 中的 TSconnect() 方法没有什么比您所看到的更多的了:drv="character", dbname="character"是函数的参数,而不是函数本身。如果您安装一些特定的数据库包并使用 showMethods("TSconnect") 您将看到该函数的所有特定实例。如果您随后使用特定的数据库驱动程序调用 TSconnect(),它将使用适当的函数。
这也是摘要等功能的工作方式。例如,尝试调用 showMethods(summary)
.根据加载的包,您应该会看到返回的多个方法
您可以在 R-Forge 上轻松查看它的源代码:http://r-forge.r-project.org/plugins/scmsvn/viewcvs.php/pkg/TSdbi/R/TSdbi.R?rev=70&root=tsdbi&view=markup .这是该功能的范围:
setGeneric("TSconnect", def= function(drv, dbname, ...) standardGeneric("TSconnect"))
setMethod("TSconnect", signature(drv="character", dbname="character"),
definition=function(drv, dbname, ...)
TSconnect(dbDriver(drv), dbname=dbname, ...))
关于r - 检查 S4 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2172146/