Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do `rlang::sym` and `rlang::quo_name` in LHS of expression behave similarly?

Call the function below using foo(c("b")). The outputs are shown inline.

I'm confused as to why both (1) df %>% mutate(!!x_ := 100 + !!x)) and (2) df %>% mutate(!!x := 100 + !!x)) work identically; based on dplyr programming recipes only (1) should work.

foo <- function(variables) {

  x <- rlang::sym(variables[[1]])

  x_ <- quo_name(x)

  print(x)
  #> b

  print(typeof(x))
  #> [1] "symbol"

  print(x_)
  #> [1] "b"

  print(typeof(x_))
  #> [1] "character"

  df <- data_frame(a = 1, b = 2)

  print(df %>% mutate(!!x_ := 100 + !!x))

  #> # A tibble: 1 x 2
  #>         a     b
  #>       <dbl> <dbl>
  #>   1     1   102  

  print(df %>% mutate(!!x := 100 + !!x))

  #> # A tibble: 1 x 2
  #>         a     b
  #>       <dbl> <dbl>
  #>   1     1   102  

}
like image 786
Shantanu Avatar asked Dec 18 '25 11:12

Shantanu


1 Answers

Moving comment to answer.

As per mentioned in the documentation you are referring to:

The rules on the LHS are slightly different: the unquoted operand should evaluate to a string or a symbol.

Here, it works because x_ is, in fact, a character.

like image 82
Steven Beaupré Avatar answered Dec 21 '25 05:12

Steven Beaupré



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!