Quosures Within an Index

I’ve written about quosures in previous posts. They can be used in functions to specify column names. But what if a column name is pulled from a loop and the value is a character? In that case, surround the value with sym().

Here is an example using only quosures.

First, the data and the function:

library(tidyverse)
library(ggplot2)
library(hrbrthemes)

people <- 600

df <- tibble(
  "id" = c(1:people),
  "performance" = c(rnorm(people, 50, 3))
)


multiply_and_plot <- function(col1){
  
  
  df <- df %>% 
    mutate(new_performance = !!col1 * 0.5)
  
  g <- ggplot(df, aes(x = !!col1)) + 
    geom_histogram(fill="#69b3a2", alpha=0.4) + 
    theme_ipsum() +
    labs(x = "Adj-Performance", y = "Frequency")
  
  return(g)
}

Using quosure:

multiply_and_plot(quo(performance))

But what if the column name is an index from a vector or for loop? Use sym().

use_cols <- c("performance")

for(i in 1:1){
  
  print(
    
  multiply_and_plot(sym(use_cols[i]))
  
  )
}

Also note that I had to include results = "asis" in the Rmarkdown document and put the function within a print command to get the output to render.

Bo\(^2\)m =)