Use character string as function argument

29,260

Solution 1

You can use eval and parse:

foo <- eval(parse(text = paste("mean(x,", myoptions, ")")))

Solution 2

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"

Solution 3

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
Share:
29,260
Kilian
Author by

Kilian

Updated on July 20, 2020

Comments

  • Kilian
    Kilian almost 4 years

    I'm sure this is simple, but I cannot find a solution ... I would like to use a variable containing a character string as argument for a function.

    x <- c(1:10)
    myoptions <- "trim=0, na.rm=FALSE"
    

    Now, something like

    foo <- mean(x, myoptions)
    

    should be the same as

    foo <- mean(x, trim=0, na.rm=FALSE)
    

    Thanks in advance!