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