2

Consider this code

fn = function(...) {
  # print the content of ... without evaluation?
}

I want the output of fn(a = b) to be "a = b" and fn(a = gn(b), 3~b~a, dd, e = 2 + f, h = hn(jn(cdf))) to be list("a=gn(b)", "3~b~a", "dd", "e=2+f", "h= hn(jn(cdf)))".

I can't seem to find the right NSE function for it. I prefer Base R so I understand the process better. The closest I got was this

fn = function(...) {
   res = rlang::enexprs(...)
   paste0(names(res), ifelse(names(res)=="",names(res) , "=") , sapply(res, capture.output))
}
xiaodai
  • 14,889
  • 18
  • 76
  • 140

2 Answers2

4

An alternative to match.call (see here) is the undocumented ...().

fn <- function(...) {
  x <- substitute(...())
  y <- ifelse(nchar(names(x)) > 0, paste(names(x), "=", x), as.character(x))
  as.list(y)
}

fn(a = b)
fn(a = gn(b), 3~b~a, dd, e = 2 + f, h = hn(jn(cdf)))
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
3

You can use match.call :

fn = function(...) {
  temp <- as.list(match.call())[-1]
  as.list(sub('^=', '', paste0(names(temp), '=', temp)))
}

fn(a = b)
#[[1]]
#[1] "a=b"

fn(a = gn(b), 3~b~a, dd, e = 2 + f, h = hn(jn(cdf)))
#[[1]]
#[1] "a=gn(b)"

#[[2]]
#[1] "3 ~ b ~ a"

#[[3]]
#[1] "dd"

#[[4]]
#[1] "e=2 + f"

#[[5]]
#[1] "h=hn(jn(cdf))"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213