2

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?

slhck
  • 36,575
  • 28
  • 148
  • 201

2 Answers2

1

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)

slhck
  • 36,575
  • 28
  • 148
  • 201
1

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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213