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)
quos. Eithervars <- quos(mpg, hp)and then yourforloop. Or something likelapply(quos(mpg, hp), gg_hist, data = mtcars). Alternatively, useaes_oraes_stringinstead ofaes, all depending on preference.