set.defaults: Set Default Arguments of a Function

View source: R/util.R

set.defaultsR Documentation

Set Default Arguments of a Function


Set the default values of formal arguments of a function.


set.defaults(f, ..., defaults)



A function


Named arguments to be set


A named list of arguments


The repetitive argument lists of many of diversitree's likelihood functions are the motivation for this function.

For example, the likelihood function that make.bisse produces takes arguments condition.surv, root, and root.p, each with default values. If you dislike the defaults, you can change them by passing in alternative values when computing likelihoods, or when doing an ML search. However, this can get tedious if you are using a function a lot, and your code will get cluttered with lots of statements like condition.surv=FALSE, some of which you may forget. See the example below for how to avoid this.


Richard G. FitzJohn


## Due to a change in sample() behaviour in newer R it is necessary to
## use an older algorithm to replicate the previous examples
if (getRversion() >= "3.6.0") {
  RNGkind(sample.kind = "Rounding")

pars <- c(0.1, 0.2, 0.03, 0.03, 0.01, 0.01)
phy <- tree.bisse(pars, max.t=30, x0=0)
lik <- make.bisse(phy, phy$tip.state)

## default arguments:
args(lik) <- set.defaults(lik, condition.surv=FALSE)

## Multiple arguments at once:
lik2 <- set.defaults(lik, root=ROOT.GIVEN, root.p=c(0, 1))

## Equivalently (using alist, not list -- see ?alist)
defaults <- alist(root=ROOT.GIVEN, root.p=c(0, 1))
lik3 <- set.defaults(lik, defaults=defaults)
identical(lik2, lik3)

diversitree documentation built on May 29, 2024, 4:38 a.m.