更新时间:2023-11-24 10:02:34
使用dec版本的ggplot2
,我们可以传递未加引号的参数,将其转换为quosure
(使用enquo
)并对其求值(
With the devel version of ggplot2
, we can pass unquoted arguments, convert it to quosure
(with enquo
) and evaluate it (!!
)
ggfun <- function(dat, x.var, y.var){
x.var <- enquo(x.var)
y.var <- enquo(y.var)
ggp <- ggplot(data = dat,
aes(x = !! x.var,
y = !! y.var)) +
geom_point()
return(ggp)
}
ggfun(dat = mtcars, x.var = drat, y.var = hp)
对于带引号的字符串,请使用sym
(来自rlang
)将其转换为符号并进行求值
For quoted strings, convert it to symbol with sym
(from rlang
) and do the evaluation
ggfun <- function(dat, x.var, y.var){
x.var <- rlang::sym(x.var)
y.var <- rlang::sym(y.var)
ggp <- ggplot(data = dat,
aes(x = !! x.var,
y = !! y.var)) +
geom_point()
return(ggp)
}
ggfun(dat = mtcars, x.var = "drat", y.var = "hp")
如果要传递带引号或不带引号,则将等价更改为字符(quo_name
),然后更改为符号(sym
)并求值(!!
)
If we want to pass either quoted or unquoted, the quosure is changed to character (quo_name
), then to symbol (sym
) and evaluate (!!
)
ggfun <- function(dat, x.var, y.var){
x.var <- rlang::sym(quo_name(enquo(x.var)))
y.var <- rlang::sym(quo_name(enquo(y.var)))
ggp <- ggplot(data = dat,
aes(x = !! x.var,
y = !! y.var)) +
geom_point()
return(ggp)
}
p1 <- ggfun(dat = mtcars, x.var = drat, y.var = hp)
p2 <- ggfun(dat = mtcars, x.var = "drat", y.var = "hp")
all.equal(p1, p2)
#[1] TRUE