tidyeval-walrus: := Operator

Description Forcing names

Description

See below

Forcing names

When a function takes multiple named arguments (e.g. dplyr::mutate()), it is difficult to supply a variable as name. Since the LHS of = is defused, giving the name of a variable results in the argument having the name of the variable rather than the name stored in that variable. This problem of forcing evaluation of names is exactly what the !! operator is for.

Unfortunately R is very strict about the kind of expressions supported on the LHS of =. This is why rlang interprets the walrus operator := as 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 also force names on its LHS:

1
2
3
4
name <- "Jane"

list2(!!name := 1 + 2)
exprs(!!name := 1 + 2)

Like =, the := operator expects strings or symbols on its LHS.

Since unquoting names is related to interpolating within a string with the glue package, we have made the glue syntax available on the LHS of :=:

1
2
list2("{name}" := 1)
tibble("{name}" := 1)

You can also interpolate defused function arguments with double braces {{, similar to the curly-curly syntax:

1
2
3
wrapper <- function(data, var) {
  data %>% mutate("{{ var }}_foo" := {{ var }} * 2)
}

Currently, forcing names with := only works in top level expressions. These are all valid:

1
2
exprs("{name}" := x)
tibble("{name}" := x)

But deep-forcing names isn't supported:

1
exprs(this(is(deep("{name}" := x))))

jesse-smith/covidsms documentation built on Dec. 25, 2021, 4:24 a.m.