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.
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)
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)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With