I am writing an R package. Within this package, I wish to have a special type of a data frame that some of the functions can recognize, with some extra attributes, say, but otherwise behaving exactly like a data frame. One way to achieve what I want is just to set some attributes on a regular data frame:
makedf <- function() {
df <- data.frame(ID=1:3)
attr(df, "myDF") <- TRUE
attr(df, "source") <- "my nose"
return(df)
}
dosmth <- function(df) {
if(!is.null(attr(df, "myDF"))) message(sprintf("Oh my! My DF! From %s!", attr(df, "source")))
message(sprintf("num of rows: %d", nrow(df)))
}
When dosmth()
receives a "myDF", it has additional information on the source of the data frame:
dosmth(data.frame(1:5))
#> num of rows: 5
dosmth(makedf())
#> Oh my! My DF! From my nose!
#> num of rows: 3
Likewise, it would be fairly simple with S3, and we could even write different variants of dosmth taking advantage of method dispatch. How do I do that with S4?