0

I want to use a very simple custom ggplot2 call inside a loop. Taking a list of variables from a dataframe to feed my function I want to obtain a plot for every variable.

This is a simplified example just for ilustrating my issue. The real function is more complex.

Function alone worked ok, but inside a loop is not working.

library(rlang) 
library(ggplot2)

gg_hist <- function(data, x){
  ggplot(data,
         aes(x = {{ x }} )) + 
    geom_histogram()
}

# This works ok

gg_hist(mtcars, hp)


# my list of variables to loop

vars <- c("mpg","hp")

for (variable in vars) {
  p <- gg_hist(mtcars, {{ variable }})
  print(p)
}


# unquoting list of variables not working either

vars <- c(mpg,hp)
1
  • 2
    You can use quos. Either vars <- quos(mpg, hp) and then your for loop. Or something like lapply(quos(mpg, hp), gg_hist, data = mtcars). Alternatively, use aes_ or aes_string instead of aes, all depending on preference. Commented Nov 5, 2020 at 17:58

1 Answer 1

2

Unless for some reason you want to be able to pass unquoted parameters, I would change the function so it only admits strings and use the .data[[]] pronoun which is the recommended way in the last versions of dplyr and ggplot. Its purpose is obvious to read when compared with quotes and bangs !! (Although someone may argue the opposite).

library(ggplot2)

gg_hist <- function(data, x){
  ggplot(data,
         aes(x = .data[[x]] )) + 
    geom_histogram()
}

gg_hist(mtcars, "hp") # Note now I use "hp" and not hp

vars <- c("mpg","hp")

for (variable in vars) {
  p <- gg_hist(mtcars, variable)
  print(p)
}

The main source for this would be the dplyr official documentation. It is true that is not a gpplot2 source but most of what is explained there is applicable. Other source for ggplot2 especifically is this rconf2020 slides. Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

This worked ok but I would be very grateful for adding documentation links on this obscure concept
I have added some sources in the answer. Hope it clarifies it a bit!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.