0

I have written a function to create ggplot:

getLRplot <- function(grid_x, grid_y, price){
  
  if(price == "reference"){
    fill = "dodgerblue4"
  }else if(price == "experience"){
    fill = "grey46"
  }else{
    fill = "black"
  }
  
  paste("netLR", price, sep= "")
  
  ggplot(BTplan, aes_string(x="noins1", y= paste("netLR", price, sep= ""))) +
    geom_point(color = "dodgerblue4") + 
    facet_grid(as.formula(paste(grid_y,"~", grid_x))) + 
    ggtitle(paste0("NET LOSS RATIO - ", toupper(price))) +
    ylab(" ") + xlab("Number Insureds") +
    geom_hline(yintercept=100, linetype="dashed", color = "dodgerblue4") +
    ylim(0,1000) +
    xlim(0,500) +
    theme(strip.background = element_rect(fill=fill, size=1.5, linetype="solid"))
}

but it only works if one specifies the iput parameter using quotes, like this:

test <- getLRplot("region1", "size", "experience")

I want to avoid using quotes, so one can say:

test <- getLRplot(region1, size, experience)

but this return an error:

Error in getLRplot(region1, size, experience) : 
  object 'experience' not found

I have tried to do different thing inside the function like: price = enquo(price) or price = c(price) etc but i always get an error. I am aware this has to do with the quotes, but i cannot figure out how to solve this?

Nneka
  • 1,764
  • 2
  • 15
  • 39
  • Have you seen existing questions and answers like these: https://stackoverflow.com/questions/48982011/r-pass-argument-to-ggplot-in-function and https://stackoverflow.com/questions/59142181/passing-unquoted-variables-to-curly-curly-ggplot-function – MrFlick Jun 22 '20 at 22:38
  • yes, i tried the `enquo()`(as described in my question), but it didnt work – Nneka Jun 22 '20 at 22:42
  • Where exactly did you put the `enquo()` and what exactly does "didn't work" mean? Did you get an error or undesired output? You need to be mindful of when switching between symbols and strings. You also might want to ask yourself if it's really worth all the trouble just to avoid typing some quotes. If you want to use functions like `paste` with variable names, you're going to need strings eventually. – MrFlick Jun 22 '20 at 22:45
  • i put ` # price = enquo(price) # grid_x = enquo(grid_x) # grid_y = enquo(grid_y)`inside the function, then run `test <- getLRplot(region1, size, experience)` and got an error `Error: Base operators are not defined for quosures.` . I have been struggling with this before, but though i give it another try. I though i must be missing something obvious, but maybe this is just tricky.... – Nneka Jun 22 '20 at 22:49
  • You should be able to adapt one of the answers from here https://stackoverflow.com/questions/62091090/purrr-dplyr-nse-issues-inside-a-user-written-function/62143109#62143109 – YBS Jun 22 '20 at 23:18

0 Answers0