Accessing tidyeval function argument as a string

Hi everyone, I'm interested in accessing a tidyeval function argument as a string for use later in the function. The following snippet works but is hard to remember and seems unwieldy:

example_function <- function(group) {
  group_string <- paste0(quo_name(enquo(group)))
  print(group_string)
}

Is there a solution that is more elegant than the above code?

Hi,

Could you explain why you want to do this in a bit more detail?

Thanks

1 Like

The immediate use case was including the variable name in the title of a ggplot chart. Here's an example:

df <- 
  tibble(
    x = 1:10,
    group_name = rep(c("Group A", "Group B"), each = 5)
  )

plot_counts <- function(subgroup) {
  df |> 
    count({{ subgroup }}) |> 
    rename(subgroup = 1) |> 
    ggplot(aes(x = subgroup, y = n)) +
    geom_col() +
    labs(title = str_c(paste0(quo_name(enquo(subgroup))), " counts"))
}

plot_counts(group_name)

It is a question of personal preference, but in such cases I usually pass the variable name as string, and then use get() to convert it to a new column, which is easy to work on. This also solves the problem with the title.

plot_counts <- function(subgroup) {
  df |> 
    mutate(sg = get(subgroup)) |> 
    count(sg) |> 
    ggplot(aes(x = sg, y = n)) +
    geom_col() +
    labs(title = str_c(subgroup, " counts"))
}

plot_counts("group_name")

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.