R: passing expression to an inner function

前端 未结 2 477
我寻月下人不归
我寻月下人不归 2021-01-07 22:35

Further delving into the mysteries of R evaluation...This is closely related to my previous question ( How to write an R function that evaluates an expression within a data-

相关标签:
2条回答
  • 2021-01-07 23:25

    You can use three dots to gather arguments and pass them to another function, is that what you mean?

    ftop=function(...) f(...)
    f=function(a,b) a[b]
    
    a=data.frame(b=10)
    
    ftop(a,"b")
    
    f(a,"b")
    
    0 讨论(0)
  • 2021-01-07 23:30

    This is most easily avoided by passing strings into topfn instead of expressions.

    topfn <- function(df, ex_txt) 
    {
      fn(df, ex_txt) 
    }
    
    fn <- function(dfr, expr_txt) 
    {        
       eval(parse(text = expr_txt), dfr) 
    }
    
    df <- data.frame(a = 1:5, b = 1:5 )
    fn(df, "a")                              
    fn(df, "2 * a + b")
    topfn(df, "a")             
    topfn(df, "2 * a + b")
    

    EDIT:

    You could let the user pass expressions in, but use strings underneath for your convenience.

    Change topfn to

    topfn <- function(df, ex) 
    {
      ex_txt <- deparse(substitute(ex))
      fn(df, ex_txt) 
    }
    topfn(df, a)             
    topfn(df, 2 * a + b)
    

    ANOTHER EDIT:

    This seems to work:

    topfn <- function(df, ex) 
    {
      eval(substitute(fn(df, ex)))
    }
    
    fn <- function(dfr, expr) 
    {        
       eval(substitute(expr), dfr) 
    }
    fn(df, a)                              
    fn(df, 2 * a + b)
    topfn(df, a)             
    topfn(df, 2 * a + b)
    
    0 讨论(0)
提交回复
热议问题