Question: Why does S4Vectors define three functions for Vector -> data.frame coercion
0
gravatar for Aditya
6 weeks ago by
Aditya120
Germany
Aditya120 wrote:

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 • 70 views
ADD COMMENTlink modified 6 weeks ago • written 6 weeks ago by Aditya120
Answer: How do the three Vector -> data.frame coercers in S4Vectors relate to each other
0
gravatar for Aditya
6 weeks ago by
Aditya120
Germany
Aditya120 wrote:

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 COMMENTlink modified 6 weeks ago • written 6 weeks ago by Aditya120
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 16.09
Traffic: 211 users visited in the last hour