R: 如何 return `fn(...)` 中 `...` 的确切形式而不评估 `...`?

R: How to return the exact form of `...` in `fn(...)` without evaluating `...`?

考虑这段代码

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

我希望 fn(a = b) 的输出为 "a = b"fn(a = gn(b), 3~b~a, dd, e = 2 + f, h = hn(jn(cdf))) 的输出为 list("a=gn(b)", "3~b~a", "dd", "e=2+f", "h= hn(jn(cdf)))"

我似乎找不到合适的 NSE 函数。我更喜欢 Base R,所以我更了解这个过程。我得到的最接近的是这个

fn = function(...) {
   res = rlang::enexprs(...)
   paste0(names(res), ifelse(names(res)=="",names(res) , "=") , sapply(res, capture.output))
}

您可以使用 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))"

match.call () 的替代方法是 未记录的 ...().

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)))