r - Using substitute() to get argument names, multiple levels up -
consider function a(), prints out argument passed in:
a <- function(x) { message("the input ", deparse(substitute(x))) } a("foo") # input "foo" tmplist <- list(x1 = 1, x2=2) a(tmplist) # input tmplist that works. when a() called function, no longer prints out original argument names:
b <- function(y) { a(y) } b("foo") # input y b(tmplist) # input y one solution seems work wrap in substitute , eval:
a1 <- function(x) { message("the input ", deparse(eval(substitute(substitute(x)), parent.frame()))) } a1("foo") # input "foo" tmplist <- list(x1 = 1, x2=2) a1(tmplist) # input tmplist b1 <- function(y) { a1(y) } b1("foo") # input "foo" b1(tmplist) # input tmplist but seems inelegant. , fails if add layer:
c1 <- function(z) { b1(z) } c1("foo") # input z is there good, general way original argument?
i'm not sure work in situations, try this:
f0 <- function(x) { nn <- substitute(x) <- 1 while(true) { on <- do.call("substitute", list(as.name(nn), parent.frame(i))) if (on == nn) break; nn <- on <- + 1 } message("the input ", nn) } f1 <-function(.f1) f0(.f1) f2 <- function(.f2) f1(.f2) and then,
> f2(foo) input foo > f1(poo) input poo > f0(moo) input moo > f2(";(") input ;( > f1(":)") input :) > f0(":p") input :p
Comments
Post a Comment