Search code examples
rfunctionvariablesggplot2quoting

Right approach for passing a variable into ggplot in a function, not to be interpreted as strings in R


My code:

function (var1, var2) {
    if (var1 = flowrate) {label <- bquote('Flow rate ('*mu~'litre)'))}
    else if (var1 = stress) {label <- bquote('Average velocity ('*m^2*s^-1*')')}
    ggplot{} + 
    ... +
    ylab(label)
}

I want the ylab(label) part to use the formula, but in this way it plots and prints it as a quoted string. E.g. when var1 = flowrate, it prints bquote('Flow rate ('*mu~'litre)') as the y axis, not interpreting the real meaning. Here is something similar, but cannot apply in my case: assigning a string to an object without double quotes

This must be a very crude way since I don't know the proper approach, but I would appreciate any suggestion for fixing this or better ways to achieve this.

Thanks for your time!


Solution

  • Here is another option using your sampleData and aes_string

    sampleData <- data.frame(Sample = sample(10:20, 8), randomNum = rnorm(8)
                             , fruit = fruit[48:55], Blender = 
                               c('a','b','c','a','b','c','a','b'))
    
    
    plot_it <- function(df, x, y, fill) {
    
      if (y == 'randomNum') {label <- bquote('Flow rate ('*mu~'litre)')}
      else if (y == 'Sample') {label <- bquote('Average velocity ('*m^2*s^-1*')')}
      else {label <- 'ylab'}
    
      ggplot(df, aes_string(x, y, fill = fill)) + 
        geom_boxplot() +
        ylab(label)
    }
    
    plot_it(sampleData, "Blender", "randomNum", 'fruit')
    

    EDIT: As aes_string is soft deprecated, here is yet another option (which seems current) using sym and !! to change the quoted string into a variable as shown here.

    plot_it_sym <- function(df, x, y, fill) {
    
      vars <- syms(c(x, y, fill))
    
      if (y == 'randomNum') {label <- bquote('Flow rate ('*mu~'litre)')}
      else if (y == 'Sample') {label <- bquote('Average velocity ('*m^2*s^-1*')')}
      else {label <- 'ylab'}
    
      ggplot(df, aes(x = !!vars[[1]], y = !!vars[[2]], fill = !!vars[[3]])) + 
        geom_boxplot() +
        ylab(label)
    }
    
    plot_it_sym(sampleData, 'Blender', 'randomNum', 'fruit')