2

I used to use mutate_ with .dots argument to evaluate a set of formulas inside a function using a mix of user supplied variables (in string format) and variables calculated inside the function (as the b variable below) as follows:

require(dplyr)
f <- function(data, a)
{
    b <- "Sepal.Length"

    mutate_call <- list(new_1 = lazyeval::interp( ~ a*10, a=as.name(a)),
                        new_2 = lazyeval::interp( ~ b*10, b=as.name(b)) )
   
    data %>%
        as_tibble() %>%
        mutate_(.dots = mutate_call) %>%
        head() %>%
        print()
    
}

f(iris, "Sepal.Width")

however, when transitioning to recent dplyr version, this is no longer possible (unless I keep using the deprecated version mutate_). How can I achieve the same result as f does using mutate instead of mutate_?

It would much easier if I could keep using the formulas.

Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74
mickkk
  • 1,172
  • 2
  • 17
  • 38

1 Answers1

2

My suggestions would be to switch from formulas to expressions, then use the unquote-splice operator !!! with regular mutate():

f <- function(data, a)
{
  # Convert strings to symbols
  a <- as.name(a)
  b <- as.name("Sepal.Length")
  
  # Use rlang::exprs to define the expressions
  # Use !! to replace a and b with the symbols stored inside them
  mutate_call <- rlang::exprs(new_1 = !!a*10, new_2 = !!b*10)

  data %>%
    as_tibble() %>%
    mutate(!!!mutate_call) %>%    # <-- !!! effectively "pastes" the expressions
    head() %>%
    print()
}

f(iris, "Sepal.Width")
# # A tibble: 6 x 7
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species new_1 new_2
#          <dbl>       <dbl>        <dbl>       <dbl> <fct>   <dbl> <dbl>
# 1          5.1         3.5          1.4         0.2 setosa     35    51
# 2          4.9         3            1.4         0.2 setosa     30    49
# 3          4.7         3.2          1.3         0.2 setosa     32    47
# 4          4.6         3.1          1.5         0.2 setosa     31    46
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74