Skip to content

Instantly share code, notes, and snippets.

@alekrutkowski
Last active August 24, 2016 09:04
Show Gist options
  • Save alekrutkowski/43bf7a4b6bd279fe08975540f7da78e8 to your computer and use it in GitHub Desktop.
Save alekrutkowski/43bf7a4b6bd279fe08975540f7da78e8 to your computer and use it in GitHub Desktop.
R function for getting the default value of a function argument
default <- function(sym) {
    Sym <- substitute(sym)
    if (!(is.symbol(Sym)))
        stop('\nExpected a symbol as an argument, got a ', class(sym))
    ArgList <- eval.parent(quote(formals()))
    ArgName <- as.character(Sym)
    if (!(ArgName %in% names(ArgList)))
        stop('\nThere is no argument named `', ArgName,'`')
    if (is.symbol(ArgList[[ArgName]]))
        stop('\nThere is no default value for argument `', ArgName,'`')
    eval.parent(ArgList[[ArgName]])
}

Usage examples:

aa <- function(alpha = c('aa','bb')) {
    stopifnot(alpha %in% default(alpha))
    alpha
}

aa('aa')
## [1] "aa"
aa('ww')
## Error: alpha %in% default(alpha) is not TRUE
bb <- function(x=1,y=10:12)
    list(X=default(x),
         Y=default(y))
bb()
## $X
## [1] 1
## 
## $Y
## [1] 10 11 12
bb(7,8)
## $X
## [1] 1
## 
## $Y
## [1] 10 11 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment