Search code examples
rggplot2

How to specify column parameters programmatically?


For the qic() function, how does one specify columns of the input data frame that are stored in string variables?

Below I attempt multiple ways to pass the "y" parameter. Given that qicharts2 is based on ggplot2 I tried some options resembling quoting for ggplot2. All failed.

my_fun <- function(y){
  require(qicharts2)

  qic(x        = i, 
      y        = .data[[y]],  # Hoping it works like ggplot2.
      n        = n, 
      data     = nhs_accidents, 
      chart    = 'p',
      title    = 'Proportion of patients seen within 4 hours',
      ylab     = NULL,
      xlab     = 'Week #')
}

my_var <- "r"
my_fun(my_var)

Error: ! Can't subset .data outside of a data mask context. Run rlang::last_trace() to see where the error occurred.

Here are some other ways I tried to define the parameter along with the errors.

y = as.symbol(my_var)

Error in stats::complete.cases(y, n) : invalid 'type' (symbol) of argument

y = {{my_var}}

Error in if (y.name == "NULL") y.name <- deparse(substitute(x)) : the condition has length > 1

y = rlang::as_label(my_var)

Error in stats::complete.cases(y, n) : not all arguments have the same length


Solution

  • This works for me:

    my_fun <- function(y_){
      require(qicharts2)
      qic(x        = i, 
          y        = eval(parse(text = y_)),
          n        = n, 
          data     = nhs_accidents, 
          chart    = 'p',
          title    = 'Proportion of patients seen within 4 hours',
          ylab     = NULL,
          xlab     = 'Week #')
    }
    
    my_var <- "r"
    
    my_fun(my_var)