Turn a {{}} (dplyr double curly braces) interpolation into a string

Viewed 274

Let's assume I have the following R function:

library(tidyverse)

f <- function(.df, .var) {
  .df %>% ggplot(aes(x = wt, y = {{ .var }})) +
    geom_point() +
    ggtitle({{ .var }})
}

f(mtcars, hp)
#> Error in list2(..., title = title, subtitle = subtitle, caption = caption, : object 'hp' not found
f(mtcars, qsec)
#> Error in list2(..., title = title, subtitle = subtitle, caption = caption, : object 'qsec' not found

Created on 2021-01-08 by the reprex package (v0.3.0)

How do I access the actual string that .var takes to use when creating a title?

2 Answers

Instead of the double curly braces, which evaluate the variable in context of the data frame, you need to use enquo to get a string:

library(tidyverse)

f <- function(.df, .var) {
  .df %>% ggplot(aes(x = wt, y = {{ .var }})) +
    geom_point() +
    ggtitle(enquo(.var))
}

f(mtcars, hp)

Created on 2021-01-08 by the reprex package (v0.3.0)

You can use deparse + substitute to change unquoted value to a string which can be used in ggtitle.

library(ggplot2)

f <- function(.df, .var) {
  title <- deparse(substitute(.var))
  
  .df %>% ggplot(aes(x = wt, y = {{ .var }})) +
    geom_point() +
    ggtitle(title)
}

f(mtcars, hp)

enter image description here

Related