18.6 Symbols

  • A symbol represents the name of an object.
    • x
    • mtcars
    • mean.
  • In base R, the terms symbol and name are used interchangeably (i.e. is.name() is identical to is.symbol()), but this book used symbol consistently because “name” has many other meanings.
  • You can create a symbol in two ways:
    1. by capturing code that references an object with expr().
    2. turning a string into a symbol with rlang::sym():.
expr(x)
#> x
sym("x")
#> x
  • A symbol can be turned back into a string with as.character() or rlang::as_string().
  • as_string() has the advantage of clearly signalling that you’ll get a character vector of length 1.
as_string(expr(x))
#> [1] "x"
  • We can recognise a symbol because it’s printed without quotes
  • str() tells you that it’s a symbol, and is.symbol() is TRUE:
str(expr(x))
#>  symbol x
is.symbol(expr(x))
#> [1] TRUE
  • The symbol type is not vectorised, i.e. a symbol is always length 1.
  • If you want multiple symbols, you’ll need to put them in a list, using rlang::syms().