r - How can I check if the passed argument exists -
i trying check if variable passed argument function exists. based on reply this question have following:
myfunction <- function(x) { stopifnot(exists(deparse(substitute(x)))) } however, not work if argument look evaluated:
a=c(1:10) myfunction(a+10) how can create sure capture non-existent variables if argument not variable?
one alternative combining match.call (returns phone call function) , all.vars (returns names in expression). seek this:
fcn <- function(x) { varnames <- all.vars(match.call()) (x in varnames) stopifnot(exists(x)) } fcn(a) # returns error, expected #error: exists(x) not true # create "a" <- 2 fcn(a + 1) # no error returned since "a" exists similarly,
fcn(a + b) # error returned since "b" not exist #error: exists(x) not true b <- 4 fcn(a + b) # no error since "b" exists r arguments
No comments:
Post a Comment