[R-pkg-devel] S4 generic with variable naming of arguments
Thomas Petzoldt
thomas.petzoldt at tu-dresden.de
Mon Feb 29 10:33:03 CET 2016
Dear colleagues,
after testing one of my packages with students, I'm trying to improve
the user interface, to make it even simpler and more robust. The package
uses S4 classes and I was very happy with this, but my aim is now to
allow non-named arguments with different ordering, depending on their
class and with and 'speaking argument names', not simply x and y.
It looks to me as this could be a FAQ and please excuse if I overlooked
something, but I still wonder. Let's assume a generic like this:
foo <- function(formula, data, grouping, ...)
It is of course easy in S4 write methods that allow either
'foo(y ~ x, df)' or 'foo(data = df, grouping = g)'
but I want to allow also 'foo(df, g)'
This works easily in S3 (see below), but [how] can this also be done
with S4 to avoid mixture of class systems in the package?
Thanks a lot!
Thomas
### Example ######################################################
foo <- function(formula, data, grouping = NULL, ...) UseMethod("foo")
foo.formula <- function(formula, data, ...) {
cat("formula method\n")
}
foo.data.frame <- function(data, grouping, ...) {
cat("data method\n")
}
foo.default <- function(data, ...)
cat("method for class", class(data), "not yet implemented\n")
df <- data.frame(x=1:10, y=runif(10), groups=rep(c("a", "b"), 5))
foo(y~x, df) # easy in S4
foo(df, grouping="groups") # easy in S3, but how in S4?
foo(1)
##################################################################
More information about the R-package-devel
mailing list