From 34bb0a5f4411147c80e1fc7fce3f936bfa70b638 Mon Sep 17 00:00:00 2001 From: Hadley Wickham Date: Thu, 8 Dec 2022 14:47:46 -0600 Subject: [PATCH] Bit more about := --- functions.qmd | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/functions.qmd b/functions.qmd index 6574b9c..7b44347 100644 --- a/functions.qmd +++ b/functions.qmd @@ -737,7 +737,7 @@ diamonds |> hex_plot(carat, price, depth) Some of the most useful helpers combine a dash of dplyr with ggplot2. For example, if you might want to do a vertical bar chart where you automatically sort the bars in frequency order using `fct_infreq()`. -Since the bar chart is vertical, we also need to reverse the usual order to get the highest values at the top (also note the `:=` operator, which allows you to inject names with glue syntax on the left-hand side of ⁠`:=`;⁠ type: ?\`:=\` for more details): +Since the bar chart is vertical, we also need to reverse the usual order to get the highest values at the top: ```{r} sorted_bars <- function(df, var) { @@ -750,6 +750,10 @@ sorted_bars <- function(df, var) { diamonds |> sorted_bars(cut) ``` +We have to use a new operator here, `:=`, because we are generating the variable name based on user-supplied data. +Variable names go on the left hand side of `=`, but R's syntax doesn't allow anything to the left of `=` except for a single literal name. +To work around this problem, we use the special operator `:=` which tidy evaluation treats in exactly the same way as `=`. + Or maybe you want to make it easy to draw a bar plot just for a subset of the data: ```{r} @@ -938,7 +942,7 @@ This makes it very obvious that something unusual is happening. f1 <- function(string, prefix) { substr(string, 1, nchar(prefix)) == prefix } - + f3 <- function(x, y) { rep(y, length.out = length(x)) }