missuse
missuse

Reputation: 19756

S3 method dispatch when argument is missing

I apologize for the vague title, could not think of anything short and specific.

I have a function foo which performs some irrelevant calculation. I have made the following methods.

foo.data.frame <- function(data, col1, col2){
  return(data.frame(col1 = data[[col1]],
                    col2 = data[[col2]]))
}

foo.list <- function(data){
  z <- unlist(data)
  d <- names(z)
  return(data.frame(col1 = z, col2 = d))
}

foo.character <- function(data){ #here data is a file address
  if(file.exists(data)){
    return(read.csv(data, row.names = 1))
  }
} 

some data:

df <- data.frame(col1 = letters[1:10],
                 col2 = 1:10)

lis <- as.list(df$col2)
names(lis) <- df$col1

write.csv(df, "df.csv")

These functions perform:

foo.data.frame(df, "col1", "col2"),
foo.list(lis)
foo.character("df.csv")

I am struggling to create a method which will take vectors as input for col1 and col2:

foo.??? <- (data = NULL, col1, col2){
  return(data.frame(col1, col2))
  }

which will be used like this:

foo(col1 = df$col1, col2 = df$col2)

This can be

foo.default 

or not

How should I go about this?

Do note that this is quite easy to do with "poor mans S3" (when all these functions are inside one, and by using an if-then-else clause to direct the object of the appropriate class to the appropriate method.

Upvotes: 4

Views: 213

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270448

You will need to handle that in the foo generic. For example,

foo.missing <- function(col1, col2) {
  data.frame(col1 = col1, col2 = col2)
}

foo <- function(data, ...) {
  if (missing(data) || is.null(data)) foo.missing(...)
  else UseMethod("foo")
}

# test    
foo(col1 = df$col1, col2 = df$col2)
foo(df, "col1", "col2"),
foo(lis)
foo("df.csv")

Upvotes: 3

Related Questions