Why does S4Vectors define three functions for Vector -> data.frame coercion
1
0
Entering edit mode
Aditya ▴ 160
@aditya-7667
Last seen 2.4 years ago
Germany

How do the three Vector -> data.frame coercers in S4Vectorsrelate to each other?

setAs("Vector", "data.frame", function(from) as.data.frame(from))

as.data.frame.Vector <- function(x, row.names=NULL, optional=FALSE, ...) {
    as.data.frame(x, row.names=NULL, optional=optional, ...)
}

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, ...)
})
S4Vectors methods • 960 views
ADD COMMENT
0
Entering edit mode
Aditya ▴ 160
@aditya-7667
Last seen 2.4 years ago
Germany

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.)

ADD COMMENT

Login before adding your answer.

Traffic: 532 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6