简体   繁体   中英

turn … of a R function into a string

In R, I want to write a function that takes in set of arguments, but doesn't evaluate them and returns the entire set of arguments as a string. I have found the following way to do this:

ff = function(...) {
  dots = dplyr::enquos(...)
  strs = sub("^[~]","=",sapply(dots,deparse))
  return(paste(paste(names(strs),strs,sep=""),collapse=","))
}

but it seems like there must be an easier, less fragile way to do this that does not depend on dplyr using the base R functions quote and deparse , but I can't figure it out.

Is there a better way to do this?

You can use match.call() :

ff = function (...) {
    args = match.call()[-1L]
    argvalues = vapply(args, deparse, character(1L))
    paste(names(args), argvalues, sep = ' = ', collapse = ', ')
}

Or, if you only want the dots, and not potential positional arguments, change just the first line of that function to

args = match.call(expand.dots = FALSE)$...

Building off of Konrad's solution above, here is the final function that I am using:

ff = function (...) {
  args = match.call(expand.dots=FALSE)$...
  argvalues = vapply(args, deparse, character(1L))
  paste(ifelse(names(args)=="",argvalues,
               paste(names(args), argvalues, sep = ' = ')),
        collapse = ', ')
}

Using this, I can do the following:

> ff(a=1,b=zzz)
[1] "a = 1, b = zzz"
> ff(a=1,zzz)
[1] "a = 1, zzz"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM