Search code examples
rdynamicargumentsscopinglexical-scope

Can you enable an R function to see the values of its own formals on evaluation?


In the R, language, suppose I have a function ff(jj, kk, mm). I would like the calling function (or calling human being in an interactive session) to be able to make mm depend in arbitrary ways on jj and kk at the time of the call.

For concreteness, suppose:

ff <- function(jj, kk, mm){
  xx <- jj + kk  
  out<- xx/mm   
  out
}

Then at run time, I want to set mm <- jj*kk. i.e.:

ff(2, 3, (jj*kk))

this yields:

Error in ff(2, 3, (jj * kk)) : object 'jj' not found

This error is not thrown until mm is evaluated, i.e. after jj and kk have already been evaluated successfully. So they are then evaluated a second time with different scoping rules. I understand that this is R-standard scoping. I am asking, can I write the function in such a way that it lets me hand mm a simple number, or a function of the other formal arguments, provided those arguments have been or can be evaluated before mm is required?

Note that I am not asking if I should do this. I will stoutly pretend to be polite to people who offer views on this latter question.

Nor am I asking if I can pre-calculate jj and hand ff the predigested number. I know this is a plausible answer, but it does not work for reasons I have simplified out of the problem.


Solution

  • As it stands, your function ff() doesn't work because supplied arguments are evaluated in the context of the calling environment, from which vantage point neither jj nor kk are 'visible'.

    To evaluate the statement supplied to mm within the context of the function's own evaluation frame, use eval(substitute()), like so:

    ff <- function(jj, kk, mm){
      mm <- eval(substitute(mm))
      xx <- jj + kk  
      out<- xx/mm   
      out
    }
    
    ff(2, 3, (jj*kk))
    ## [1] 0.8333333