Search code examples
revalenvironmentrlang

Evaluate expression with in-function variable calculation


Basically, I want to create an add_trend function that will bind to the original dataset. However, I want to do it using an expression. For example .t = linear trend, .t + .t^2 = quadratic trend.

.data <- tibble::tibble(
  x = rnorm(100),
  y = rnorm(100))


add_trend <- function(.data, .f = NULL) {

  .t <- 1:NROW(.data)

  .expr <- quote(.f)
  eval(.expr)
}

add_trend(.data, .t^2)
#> Error in eval(.expr): object '.t' not found

Created on 2019-03-07 by the reprex package (v0.2.1)

It has to do something with the environment that it is evaluated. If I store .t in the Global_Env then the function works, but when it's done inside the function then the above error shows up. Any help would be very appreciated.


Solution

  • Using substitute rather than quote:

    add_trend <- function(.data, .f = NULL) {
      .t <- 1:NROW(.data)
      .expr <- substitute(.f)
      eval(.expr)
    }
    

    From help("quote")

    substitute returns the parse tree for the (unevaluated) expression expr, substituting any variables bound in env.

    quote simply returns its argument. The argument is not evaluated and can be any R expression.