问题描述
This问题讨论了这个问题,但是我需要通过我的函数传递对象。例如:
foo <- function(data,col1,col2) {
Boxplot(
formula = col1 ~ col2,data = data)
}
运行此命令时:
foo(data,col2)
我得到object 'col1' not found
。
如何通过col1
和col2
?
解决方法
在base R
中,我们可以通过先用deparse/substitute
转换为字符串,然后使用paste
创建公式,从无引号的引数构造公式
foo <- function(data,col1,col2) {
col1 <- deparse(substitute(col1))
col2 <- deparse(substitute(col2))
boxplot(
formula = as.formula(paste0(col1,"~",col2)),data = data)
}
-使用内置数据集对其进行测试
foo(mtcars,mpg,cyl)
或者,如果我们更喜欢使用tidyverse
,请使用卷曲卷曲({{..}}
)运算符同时转换为法定量(enquo
)和求值(!!
)
library(dplyr)
library(ggplot2)
foo2 <- function(data,col2) {
data %>%
select({{col1}},{{col2}}) %>%
mutate( {{col2}} := factor({{col2}})) %>%
ggplot(aes(x = {{col2}},y = {{col1}})) +
geom_boxplot()
}
foo2(mtcars,cyl)