Suppose I have a character vector that contains the name of a function, such as basename
, or stringr::fixed
. I would like to:
- Determine whether that function can be called in the current environment, and
- Call the function using a list of arguments as with
do.call
.
My thought was this:
fn_chr = 'basename'
f = get0(fn_chr)
if(is.null(f) | !is.function(f)) stop('Function does not exist.')
args = list(pattern = 'w')
do.call(f, args)
[ignore the fact that pattern is not a valid argument for basename]
But this does not work for, say, stringr::fixed
-
fn_chr = 'stringr::fixed'
f = get0(fn_chr)
if(is.null(f) | !is.function(f)) stop('Function does not exist.')
args = list(pattern = 'w')
do.call(f, args)
get0
does not find the function, and do.call
, even if given the string, won't find it either.
do.call(fn_chr, args)
# Error in `stringr::fixed`(pattern = "w") :
# could not find function "stringr::fixed"
But I have stringr
installed, so
stringr::fixed(pattern = "w")
works fine.
How can I construct the function call that I want?