Art
Art

Reputation: 43

Function that can recieve different type of arguments

I'm trying to write function that can receive only data frame contains two numeric vectors or two numeric vectors. But I cannot write if function properly.

lad=function(...){
  z=(...);
if (!is.data.frame(z) & length(z)!=2 | !is.vector(z[[1]] & !is.vector(z[[2]] & length(z[[1]])!=length(z[[2]])) stop ('arguments must contain data frame or two vectors')

}

Where is the problem here? function may contain lad(x,y) or lad(z) where z=data.frame(x,y)

Upvotes: 0

Views: 56

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269471

Normally this is done using S3 or S4. Using S3 we create a generic with methods for data.frame and for default (which handles the other case):

lad <- function(x, ...) UseMethod("lad")
lad.data.frame <- function(x, ...) x
lad.default <- function(x, y, ...) lad(data.frame(x, y), ...)

lad will dispatch calls with data.frame arguments to lad.data.frame and all other calls to lad.default so if you need to implement further checks those are the places to put them.

In the example above we just return a data frame but in your actual code replace that with something more useful.

Here are two examples of calling lad (where BOD is a data frame that comes with R):

lad(BOD)
lad(1:10, 11:20)

Upvotes: 3

Related Questions