For completeness, I think it's safer to use column names instead of indices because column positions within a data frame can be changed causing unexpected results.
The plot_duo
function below (taken from this answer) can use input either as strings or bare column names
library(rlang)
library(purrr)
library(dplyr)
library(ggplot2)
theme_set(theme_classic(base_size = 14))
set.seed(123456)
testdata <- data.frame(v1 = rnorm(100), v2 = rnorm(100), v3 = rnorm(100),
v4 = rnorm(100), v5 = rnorm(100))
plot_duo <- function(df, plot_var_x, plot_var_y) {
# check if input is character or bare column name to
# use ensym() or enquo() accordingly
if (is.character(plot_var_x)) {
print('character column names supplied, use ensym()')
plot_var_x <- ensym(plot_var_x)
} else {
print('bare column names supplied, use enquo()')
plot_var_x <- enquo(plot_var_x)
}
if (is.character(plot_var_y)) {
plot_var_y <- ensym(plot_var_y)
} else {
plot_var_y <- enquo(plot_var_y)
}
# unquote the variables using !! (bang bang) so ggplot can evaluate them
pts_plt <- ggplot(df, aes(x = !! plot_var_x, y = !! plot_var_y)) +
geom_point(size = 4, alpha = 0.5)
return(pts_plt)
}
Apply plot_duo
function across columns using purrr::map()
### use character column names
plot_vars1 <- names(testdata)
plt1 <- plot_vars1 %>% purrr::map(., ~ plot_duo(testdata, .x, "v1"))
#> [1] "character column names supplied, use ensym()"
#> [1] "character column names supplied, use ensym()"
#> [1] "character column names supplied, use ensym()"
#> [1] "character column names supplied, use ensym()"
#> [1] "character column names supplied, use ensym()"
str(plt1, max.level = 1)
#> List of 5
#> $ :List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#> $ :List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#> $ :List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#> $ :List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#> $ :List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
# test plot
plt1[[3]]

### use bare column names
# Ref: https://stackoverflow.com/a/49834499/
plot_vars2 <- rlang::exprs(v2, v3, v4)
plt2 <- plot_vars2 %>% purrr::map(., ~ plot_duo(testdata, .x, rlang::expr(v1)))
#> [1] "bare column names supplied, use enquo()"
#> [1] "bare column names supplied, use enquo()"
#> [1] "bare column names supplied, use enquo()"
str(plt2, max.level = 1)
#> List of 3
#> $ :List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#> $ :List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#> $ :List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
plt1[[2]]

Created on 2019-02-18 by the reprex package (v0.2.1.9000)