0

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.

4
  • 2
    The error its telling you that it can not find the foward pipe operator (%>%). You must load dplyr / tidyverse packages first. Commented Mar 7, 2019 at 2:27
  • 1
    It's also very odd to prefix all your functions with periods. That usually means they are "hidden" variables. Is that really what you want? Are you trying to use the rlang evaluation? Because quote() and eval() are base R functions, not rlang versions. Commented Mar 7, 2019 at 3:01
  • @SantiagoCapobianco it was a bad reprex, the problem is not in the pipe. Commented Mar 7, 2019 at 3:28
  • @MrFlick I don't know If I know the theory about the dot-suffix I just do it to get around conflicts. What do you suggest? enexpr - eval_bare or is there another way? Commented Mar 7, 2019 at 3:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.