Use character string as function argument
A more natural way to do what you want is to use do.call
. For example,
R> l[["trim"]] = 0
R> l[["na.rm"]] = FALSE
R> l[["x"]] = 1:10
##Or l <- list(trim = 0, na.rm = FALSE, x = 1:10)
R> do.call(mean, l)
[1] 5.5
If for some reason you really want to use a myoptions
string, you could always use strsplit
to coarce it into a list form. For example,
R> y = "trim=0, na.rm=FALSE"
R> strsplit(y, ", ")
[[1]]
[1] "trim=0" "na.rm=FALSE"
R> strsplit(y, ", ")[[1]][1]
[1] "trim=0"
You can use eval
and parse
:
foo <- eval(parse(text = paste("mean(x,", myoptions, ")")))
Here's a third answer that both uses parse
, alist
and do.call
. My motivation for this new answer, is in the case where arguments are passed interactively from a client-side as chars. Then I guess, there is no good way around not using parse
. Suggested solution with strsplit
, cannot understand the context whether a comma ,
means next argument or next argument within an argument. strsplit
does not understand context as strsplit
is not a parser.
here arguments can be passed as "a=c(2,4), b=3,5"
or list("c(a=(2,4)","b=3","5")
#' convert and evaluate a list of char args to a list of arguments
#'
#' @param listOfCharArgs a list of chars
#'
#' @return
#' @export
#'
#' @examples
#' myCharArgs = list('x=c(1:3,NA)',"trim=0","TRUE")
#' myArgs = callMeMaybe(myCharArgs)
#' do.call(mean,myArgs)
callMeMaybe2 = function(listOfCharArgs) {
CharArgs = unlist(listOfCharArgs)
if(is.null(CharArgs)) return(alist())
.out = eval(parse(text = paste0("alist(",
paste(parse(text=CharArgs),collapse = ","),")")))
}
myCharArgs = list('x=c(1:3,NA)',"trim=0","TRUE")
myArgs = callMeMaybe2(myCharArgs)
do.call(mean,myArgs)
[1] 2