Search code examples
rargumentsoptional-arguments

access choices from formal argument of function


Is there a way to access the choices of an argument of a function?

In this silly example:

noise <- function(animal = c("dog","cat","chicken","pig")){ # default animal is "dog"
  animal <- match.arg(animal)
  sound <- c("woof","meow","cluck","oink")[match(animal, c("dog","cat","chicken","pig"))]
  sound
}
noise("chicken") # returns desired result

I would like to avoid retyping c("dog","cat","chicken","pig") by accessing the vector of choices from the declaration, something similar to (making this up):

noise <- function(animal = c("dog","cat","chicken","pig")){ 
      animal <- match.arg(animal)
      sound <- c("woof","meow","cluck","oink")[match(animal, self.choices("animal"))]
      sound
    }

Solution

  • try this: eval(formals(noise)[["animal"]])