1

I'm trying to pass an expression in a nested series of functions. Here is a simplified example of work that I want to do:

require(shiny)
outterfunc <- function(a,b,expr){
  innerfunc <- function(a,b, expr){
    shiny::exprToFunction(expr,quoted = F)()
  }
  return(innerfunc(a = a+1,b= b+1, expr=expr))
}

I expect to get this result when I'm running following commands:

outterfunc(2,5,{a*b})
# 18

which give me error like

# Error in exprToFunction(expr, quoted = F)() : object 'b' not found

I managed to solve issue with using eval(parse(text=paste(...... sequence, but I'm wondering is there any clean way to pass expression between nested functions.

Thank you in advance for reading this.

2
  • Where does exprToFunction come from? Be sure to include references to all relevant packages. Commented Jun 11, 2015 at 16:01
  • Thanks for the reply and sorry for inconvenience with the exprToFunction. I was using this so widely that I forgot it is not the base function :) Commented Jun 11, 2015 at 16:20

1 Answer 1

3

In this particular case, It seems like this will work

outterfunc <- function(a,b,expr){
  innerfunc <- function(a,b, expr){
    ex <- eval(substitute(substitute(expr)),parent.frame())
    eval(ex, environment())
  }
  return(innerfunc(a = a+1,b= b+1, expr=expr))
}

outterfunc(2,5,{a*b})
# [1] 18

First you need to grab the unevaluated expression from two levels up, then you evaluate it within the current parameter value context.

Sign up to request clarification or add additional context in comments.

1 Comment

Dealing with a similar nested expression problem and I never would of figured this out on my own. Thanks for sharing this solution! Can you point me towards any resources to help me better understand how/when to use nested eval/substitute calls?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.