substitution - R - using substitute within a nested function -



substitution - R - using substitute within a nested function -

i have function may end beingness nested (inner) , other function (in general function won't known) i'm calling outer, , inner able produce same result regardless of wrapper function (outerin below case).

inner <- function(x,baz,bang){ # code stuff things ... x.prime = as.character(substitute(x)) return(c(x.prime,y,z)) } outer <- function(y){ inner(y) } inner(a) # "a" "stuff" "things" , i'm expecting, in particular "a". outer(a) # "y" .... , expecting "a"?

of course of study i'm not dead set on using substitute if knows of improve method.

does have clues how inner output same result regardless if nested or not?

thanks in advance.

here general outline should help solve problem:

inner <- function(x) { my.call <- quote(substitute(x)) # quote here because going re-use look var.name <- eval(my.call) for(i in rev(head(sys.frames(), -1l))) { # first frame doesn't matter since substituted first level, reverse since sys.frames in order of evaluation, , want go in reverse order my.call[[2]] <- var.name # re-use it, modified replace variable var.name <- eval(my.call, i) } return(var.name) } outer <- function(y) inner(y) outer2 <- function(z) outer(z)

now let's run functions:

inner(1 + 1) # 1 + 1 outer(2 + 2) # 2 + 2 outer2(3 + 3) # 3 + 3

inner returns outermost look (you don't see y or z ever, look typed in .globalenv.

the trick here utilize sys.frames(), , repeatedly substitute until top level.

note assumes "outer" functions forwards argument on next inner one. things lot more complicated / impossible if have like:

outer <- function(y) inner(y + 1)

this code not check type of issue, should in code. also, maintain in mind assumption here functions called r command line. if wraps functions around yours, might unexpected results.

r substitution

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -