tidyeval difference between mutate `:=` and mutate `=`

Viewed 426

Both these code blocks work even though they use different equal signs, one with := and the other with =. Which is correct and why? I thought tidyeval required := when using dplyr functions, but strange enough = works just fine in my mutate call.

1

library(tidyverse)
set.seed(1)
graph.data <- tibble(cal.date = as.Date(40100:40129, origin = "1899-12-30"), 
                     random_num = rnorm(30, 8, 5))

child_function <- function(df, variable, hor.line = 6) {  
  variable <- enquo(variable)
  df <- mutate(df, mutation := 2 * !! variable, horizontal.line := hor.line)
  df
}

child_function(graph.data, variable = random_num, hor.line=8)

2

library(tidyverse)
set.seed(1)
graph.data <- tibble(cal.date = as.Date(40100:40129, origin = "1899-12-30"), 
                     random_num = rnorm(30, 8, 5))

child_function <- function(df, variable, hor.line = 6) {  
  variable <- enquo(variable)
  df <- mutate(df, mutation = 2 * !! variable, horizontal.line = hor.line)
  df
}

child_function(graph.data, variable = random_num, hor.line=8)
3 Answers

The := operator's purpose is to allow you to dynamically set the name of variable on the LHS (left hand side) of the equation, which you are not doing here.

In many cases, including this one, we're just concerned with manipulating the RHS. The := would come in handy if you wanted to control the name of the "mutation" variable.

https://dplyr.tidyverse.org/articles/programming.html#setting-variable-names

There is no obligation to put := in that case.

It becomes obligatory when you want to do something like:

child_function <- function(df, variable, hor.line = 6, mt_name = "mutation") {  

  variable <- enquo(variable)

  df <- mutate(df, !! mt_name := 2 * !! variable, horizontal.line = hor.line)

}

A little bit hard to track down, but from ?quasiquotation

Unfortunately R is very strict about the kind of expressions supported on the LHS of =. This is why we have made the more flexible := operator an alias of =. You can use it to supply names, e.g. a := b is equivalent to a = b. Since its syntax is more flexible you can unquote on the LHS:

Related