[R] distinguishing input objects for a function

Duncan Murdoch murdoch.duncan at gmail.com
Wed Oct 3 12:06:55 CEST 2012

On 12-10-03 1:59 AM, ishi soichi wrote:
> platform       x86_64-apple-darwin9.8.0
> arch           x86_64
> os             darwin9.8.0
> system         x86_64, darwin9.8.0
> version.string R version 2.13.1 (2011-07-08)
> I am trying to write a function that takes a few objects as input.
> test <- function(directory, num = 1:100) {
>> }
> the argument, "num", has the default value. But when the function is
> called, it can take an array as well,
> test("directory", c(1, 2, 3))

I don't understand the question.  You've passed the vector 1:3 as the 
num argument (by position).   Do you want to prevent someone from 
passing an array?

> I can parse the both arguments by converting them into string, but I am
> wondering if there is a better (more efficient) way to achieve this.

I don't understand what you want to achieve.

> Perhaps, using built-in R functions can help, I suppose?
> Does anyone have any idea for the function taking more than one kind of
> argument?

In most functions, R allows any type of argument in any position.  If 
your function only works for one type, usually an error will follow, but 
you can add your own tests for better error messages.  For example,


will trigger an error if num is a non-numeric object.  See also stop() 
for an unconditional error (presumably controlled by an if()).

Duncan Murdoch

More information about the R-help mailing list