Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

function

r

dplyr

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)
like image 291
stackinator Avatar asked Mar 18 '26 18:03

stackinator


2 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

like image 111
Jon Spring Avatar answered Mar 21 '26 09:03

Jon Spring


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)

}
like image 26
arg0naut91 Avatar answered Mar 21 '26 07:03

arg0naut91



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!