GregRousell
GregRousell

Reputation: 1077

How do I create a new object in an R function, that I can use within the function

I'm trying to write a function that will create a ggplot that has components all based on a single input. I have a data frame with race, results on three assessments (reading, writing, math) plus the confidence interval for each result. I want to create a function that will create the same plot based on Read, Write or Math.

For example, this works if I use the var Read_perc

library(tidyverse)
dat <- data.frame (Race = c("White", "Black", "Inidigenous"),
                  Read_perc = c (0.756, 0.592, 0.548),
                  Read_low_ci = c (0.742, 0.498, 0.467),
                  Read_high_ci = c(0.769, 0.679, 0.628),
                  Write_perc = c (0.717, 0.625, 0.497),
                  Write_low_ci = c (0.703, 0.532, 0.416),
                  Write_high_ci = c (0.731, 0.710, 0.578))

my_plot_function <- function (df, var){
  var <- enquo(var)
  df %>% 
    ggplot (aes (x = reorder (Race, !! var), y = !! var)) +
    geom_col () +
    coord_flip () +
    geom_text (aes (label = scales::percent(!! var, accuracy = 1)),
               y = 0.05,
               colour = "white")

}

my_plot_function(dat, Read_perc)

However, I want to use just Read or Write, and then use it to call different columns, like Read_perc, Read_low_ci, etc.

For example, this doesn't work:

my_plot_function <- function (df, var){

var <- enquo (var)
var_low_ci <- paste0 (var, "_low_ci")
var_high_ci <- paste0 (var, "_high_ci")

df %>% 
    ggplot (aes (x = reorder (Race, !! var), y = !! var)) +
    geom_col () +
    coord_flip () +
    geom_text (aes (label = scales::percent(!! var, accuracy = 1)),
               y = 0.05,
               colour = "white") +
       geom_errorbar(aes(ymin = var_low_ci,
                         ymax = var_high_ci),
                         colour = "black")

The final chart should look something like this:

enter image description here

Upvotes: 2

Views: 44

Answers (1)

akrun
akrun

Reputation: 887038

We can convert to symbol an evaluate

my_plot_function <- function (df, var){

   var <- rlang::as_string(rlang::ensym(var))
   var_low_ci <- rlang::sym(str_c(str_remove(var, "_perc"), "_low_ci"))
   var_high_ci <- rlang::sym(str_c(str_remove(var, "_perc"), "_high_ci"))
    var1 <- rlang::sym(var)

  df %>% 
    ggplot(aes(x = reorder(Race, !! var1), y = !! var1)) +
    geom_col () + 
    coord_flip () +
           geom_text(aes(label = scales::percent(!! var1, accuracy = 1)),
                      y = 0.05,
                      colour = "white") +
              geom_errorbar(aes(ymin = !!var_low_ci,
                                ymax = !!var_high_ci),
                                colour = "black")
}

-testing

my_plot_function(dat, Read_perc)

enter image description here

Upvotes: 3

Related Questions