1) setAs()
provides a dynamic coercion mechanism, so is useful for as(x, class)
when class can be anything.
setAs("Vector", "data.frame", function(from) as.data.frame(from))
2) as.data.frame()
is an S3 generic defined by the base
package, so every package sees it.
Something promotes as.data.frame() to an S4 generic
, but only packages that import the generic can see it. That likely excludes the vast majority of CRAN packages. Thus, we define an S3 method for calls to the S3 generic
.
as.data.frame.Vector <- function(x, row.names=NULL, optional=FALSE, ...) {
as.data.frame(x, row.names=NULL, optional=optional, ...)
}
3) The S4 generic will fall back to the S3 methods; however, it will first check all S4 methods. Defining as.data.frame,Vector() defends against the definition of a method above it, such as as.data.frame,Annotated(), which would intercept dispatch to the S3 as.data.frame.Vector().
setMethod("as.data.frame",
"Vector",
function(x, row.names=NULL, optional=FALSE, ...){
x <- as.vector(x)
as.data.frame(x, row.names=row.names, optional=optional, ...)
})
(Thank you, Michael Lawrence for clarifying this on bioc-devel, which I wrote down here for future reference purposes.)