How do I pass the expression "from a higher level" to mutate?

I would like to create a higher level function that completes the mutation. I want to give an expression parameter to my function and be able to use that expression in mutate:

datas <- data.frame(x = sample(100))
fn <- function(datas, expr) {
   mutate(datas, flag = eval(substitute(expr), datas))
}

fn(datas[1], x > 50)
Error in mutate_impl(.data, dots) : object 'x' not found 

      

But I don't understand why it fails as it mutate(datas, flag = eval(substitute(x > 50), datas))

works.

What am I doing wrong?

thank

+3


source to share


2 answers


Try the following:

fn <- function(df, expr)
eval(substitute(mutate(df, expr), list(expr=substitute(expr))))

      



or (preferably):

fn <- function(df, expr)
mutate_(df, .dots= list(flag=substitute(expr)))

      

+4


source


Best used dplyr::mutate_

, which is intended for this kind of scenarios where non-standard evaluation is problematic inside a function.

fn <- function(datas, expr) {
  expr <- substitute(expr)
  dplyr::mutate_(datas, flag = expr)
}

      



See http://adv-r.had.co.nz/Computing-on-the-language.html#calling-from-another-function and vignette("nse")

.

+3


source







All Articles