为了完整起见,我认为使用列名而不是索引更安全,因为数据框中的列位置可能会更改,从而导致意外结果。
下面的plot_duo
函数(取自这个答案)可以使用输入作为字符串或裸列名
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)
}
plot_duo
使用跨列应用函数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]]
由reprex 包于 2019-02-18 创建(v0.2.1.9000)