Skip to contents

kwb.default

This package provides functions that allow you to change the default behaviour of your user defined functions.

Installation

You can install the latest development version of the package kwb.default from github with

# install.packages("devtools")
devtools::install_github("kwb-r/kwb.default")

Usage

First of all, you need to load the package:

Setting default values

Instead of setting constant values in your function’s definition, you can use calls to getDefault() that look up the current default values for the function’s arguments when you call the function without these arguments being set. So, instead of defining a function hello1() with constant default values "Mona" and "Lisa" for the formal arguments firstName and lastName, respectively:

hello1 <- function
(
  firstName = "Mona", 
  lastName = "Lisa"
) 
{
  cat(paste0("Hello ", firstName, " ", lastName, "!\n"))
}

you define the function by assigning calls to getDefault() as default values, like this:

hello2 <- function
(
  firstName = getDefault("hello2", "firstName"),
  lastName = getDefault("hello2", "lastName")
) 
{
  cat(paste0("Hello ", firstName, " ", lastName, "!\n"))
}

You then set the default values separately with setDefault():

setDefault("hello2", firstName = "Mona", lastName = "Lisa")

Both functions now behave in the same way:

hello1()
## Hello Mona Lisa!
hello2()
## Hello Mona Lisa!

However, for hello2() we can easily change the default values without having to update the function’s definition, just by calling setDefault() again:

setDefault("hello2", firstName = "Don", lastName = "Quichote")

If you call the function now without arguments, the new defaults are used:

hello2()
## Hello Don Quichote!

Note that setDefault() will raise an error if the function specified does not exist

tryCatch(setDefault("hello", firstName = "Peter"))
## Error in get(parts[1]) : object 'hello' not found
## Error: 'hello' does not seem to be a function!

Getting default values

To read the current settings of default values, use getDefault():

getDefault("hello2", "firstName")
## [1] "Don"
getDefault("hello2", "lastName")
## [1] "Quichote"