R的S3 OO系统以泛型函数为中心,这些泛型函数根据调用泛型函数的对象类调用方法。关键在于泛型函数调用适当的方法,而不是使用其他OO编程语言在类中定义方法。
例如,mean函数是一个泛型函数。
isGeneric("mean")
methods(mean)这将打印出来
TRUE
[1] mean,ANY-method mean.Date mean.default mean.difftime
[5] mean.IDate* mean,Matrix-method mean.POSIXct mean.POSIXlt
[9] mean,sparseMatrix-method mean,sparseVector-method
see '?methods' for accessing help and source code我对R进行了一些探索,找到了as函数。令我困惑的是,R说函数不是泛型的,但它仍然有方法。
isGeneric("as")
methods(as)
TRUE
[1] as.AAbin as.AAbin.character
[3] as.alignment as.allPerms
[5] as.array as.array.default
[7] as.binary as.bitsplits
[9] as.bitsplits.prop.part as.call
... 最后会出现一条警告,说明as不是泛型。
Warning message:
In .S3methods(generic.function, class, parent.frame()) :
function 'as' appears not to be S3 generic; found functions that look like S3 methods谁能给我解释一下as函数是什么,以及如何连接到as.list,as.data.frame等?R说as.list是一个泛型(我对R中的不一致感到有点生气,因为我希望as.list是来自as泛型函数的list对象的方法)。请帮帮忙。
发布于 2018-01-15 02:50:16
as不是S3泛型,但请注意,您得到了一个TRUE。(我得到了一个FALSE。)这意味着您已经加载了一个将as定义为S4-generic的包。S3-泛型通过使用*.default函数和UseMethod-function的类分派工作。我得到的FALSE表示没有为泛型as定义的方法可以查找。没有通用as的一个有争议的原因是,只用一个数据对象调用这样的函数不会指定“强制目标”。这意味着需要将目的地构建到函数名中。
在声明as为泛型之后(注意大写,这是一个提示,这适用于S4特性:
setGeneric("as") # note that I didn't really even need to define any methods
get('as')
#--- output----
standardGeneric for "as" defined from package "methods"
function (object, Class, strict = TRUE, ext = possibleExtends(thisClass,
Class))
standardGeneric("as")
<environment: 0x7fb1ba501740>
Methods may be defined for arguments: object, Class, strict, ext
Use showMethods("as") for currently available ones.如果我重新启动R(并且没有加载任何为‘as’调用setGeneric的库),我会得到:
get('as')
#--- output ---
function (object, Class, strict = TRUE, ext = possibleExtends(thisClass,
Class))
{
if (.identC(Class, "double"))
Class <- "numeric"
thisClass <- .class1(object)
if (.identC(thisClass, Class) || .identC(Class, "ANY"))
return(object)
where <- .classEnv(thisClass, mustFind = FALSE)
coerceFun <- getGeneric("coerce", where = where)
coerceMethods <- .getMethodsTable(coerceFun, environment(coerceFun),
inherited = TRUE)
asMethod <- .quickCoerceSelect(thisClass, Class, coerceFun,
coerceMethods, where)
.... trimmed the rest of the code但你会问“为什么”,当然,在讨论语言设计时,这总是一个危险的问题。我已经翻阅了S中的统计模型的最后一章,这是适用于S3调度的大多数帮助页面的引用参考,并且没有发现任何关于强制或as函数的讨论。"S3泛型“有一个隐含的定义,需要使用UseMethod,但没有提到为什么as被排除在该策略之外。我认为有两种可能性:一种是防止在强制应用中出现任何形式的继承歧义,另一种是效率决定。
我可能应该补充说,有一个S4 setAs-function,您可以使用showMethods("coerce")找到所有的S4强制函数。
https://stackoverflow.com/questions/48252241
复制相似问题