Uses the eval_tidy() function to evaluate an expression within the context of the data and env arguments. It provides two additional elements of flexibility:

  • data does not need to be named, if it isn't named, it can be references by . or .data.

  • expr can be a function (preferably a fseq object) that will be applied to data. What's more is that expr will be evaluated through eval_tidy() before being applied and so functions defined within data can also be used.

Note the data argument is first (whereas in eval_tidy(), it is second) to keep in line with the pipeline theme of mpipe.

eval_expr(data, expr, ..., env = NULL, allow_NULL = F, verbose = F)

Arguments

data

data within which to evaluate. Used as a data mask in eval_tidy()

expr

a call, function or expression to be evaluated within the context of data

...

additional arguments to be attached to data during evaluation.

env

the environment in which to evaluate the expression

allow_NULL

logical. Can eval_expr() return a NULL value? By default, NULLs will result in an error.

verbose

logical. Should eval_expr() be chatty?

Examples

# Can do simple evaluations of functions on vectors 1:10 %>% eval_expr(mean)
#> [1] 5.5
# Or on a variable x <- 1:10 eval_expr(x, mean)
#> [1] 5.5
# or within a data.frame (or tibble) tbl <- data.frame(x = 1:10) eval_expr(tbl, mean(x))
#> [1] 5.5
# or a list lst <- list(x = 1:10) eval_expr(lst, mean(x))
#> [1] 5.5
# functions are applied to data eval_expr(tbl, nrow)
#> [1] 10
# but they are evaluated within data first lst <- c(fun = mean, lst) eval_expr(lst, fun(x))
#> [1] 5.5
# additional named arguments can be passed in too tbl %>% eval_expr(mean(x + y), y = 5)
#> [1] 10.5
x %>% eval_expr(. %>% magrittr::add(y) %>% mean(), y = 5)
#> [1] 10.5
# Environment scope: lst <- list(x = 1:3, y = 1) y <- 4 e1 <- new.env(parent = emptyenv()) e1$y <- 3 # additional arguments in data take priority over others eval_expr(lst, y, y = 2, env = e1)
#> [1] 1
lst$y <- NULL # then the ... argument: eval_expr(lst, y, y = 2, env = e1)
#> [1] 2
# then in env eval_expr(lst, y, env = e1)
#> [1] 3
# without env, the calling environment is used eval_expr(lst, y)
#> [1] 4