在ggplot2中,您可以使用aes_string
在用户定义的函数内传递字符参数。对于采用公式而不是aes
?
FUN <- function(data, x, y, fac1, fac2) {
ggplot(data = data, aes_string(x=x, y=y)) +
geom_point() + facet_grid(as.formula(substitute(fac1 ~ fac2)))
}
FUN(mtcars, 'hp', 'mpg', 'cyl', 'am')
答案 0 :(得分:30)
reformulate()
似乎工作正常。
FUN <- function(data, x, y, fac1, fac2) {
ggplot(data = data, aes_string(x=x, y=y)) +
geom_point() + facet_grid(reformulate(fac2,fac1))
}
FUN(mtcars, 'hp', 'mpg', 'cyl', 'am')
答案 1 :(得分:3)
借助 rlang
魔术和新的 ggplot2 v3.0.0
功能,您可以执行以下操作:
FUN <- function(data, x, y, fac1, fac2) {
ggplot(data = data, aes(x = !!ensym(x), y = !!ensym(y))) +
geom_point() +
facet_grid(eval(expr(!!ensym(fac1) ~ !!ensym(fac2))))
}
FUN(mtcars, 'hp', 'mpg', 'cyl', 'am')
请注意,我们不使用已过时的aes_string
。
在这些情况下,我个人喜欢使用称为glue_formula
的函数(引用程序包glue
):
glue_formula <- function(.formula, .envir = parent.frame(), ...){
formula_chr <- gsub("\\n\\s*","",as.character(.formula)[c(2,1,3)])
args <- c(as.list(formula_chr), .sep=" ", .envir = .envir)
as.formula(do.call(glue::glue, args),env = .envir)
}
FUN2 <- function(data, x, y, fac1, fac2) {
ggplot(data = data, aes(x = !!ensym(x), y = !!ensym(y))) +
geom_point() + facet_grid(glue_formula({fac1} ~ {fac2}))
}
FUN2(mtcars, 'hp', 'mpg', 'cyl', 'am')
它没有经过tidyverse批准(see interesting discussion here),但对我来说很好。