Search code examples
rfunctiondplyrrlang

What does `sym()` do regarding tidyeval?


library(tidyverse)
input_name <- "birth_year"
input_value <- 19

quo(filter(starwars, !!input_name == !!input_value))       # line 5
quo(filter(starwars, !!sym(input_name) == !!input_value))  # line 6

What's the difference between line #5 and line #6, and the use of the sym() function? Why is sym() only required on the left side of the equation in line #6?

Is the point of sym() to take character strings and unquote them into symbols?

Line 5

<quosure>
  expr: ^filter(data, "birth_year" == 19)
  env:  global

Line 6

<quosure>
  expr: ^filter(data, birth_year == 19)
  env:  global

Solution

  • In the first case, the column is not evaluated, it is the string that gets evaluated. But, by converting to symbol and evaluate it, it returns the column values. The sym is required in the lhs because we are not trying to get the literal value, but to extract the column value

    According to ?sym

    sym() creates a symbol from a string and syms() creates a list of symbols from a character vector.

    and the ?"!!"

    The !! operator unquotes its argument. It gets evaluated immediately in the surrounding context.