为什么这个函数执行失败?
my_ttest <- function(df, variable, by){
variable <- enquo(variable)
by <- enquo(by)
t.test(!!variable ~ !!by, df)
}
my_ttest(mtcars, mpg, am) Error in is_quosure(e2) : argument "e2" is missing, with no default
但这个有效
my_mean <- function(df, variable, by){
variable <- enquo(variable)
by <- enquo(by)
df %>% group_by(!!by) %>% summarize(mean(!!variable))
}
my_mean(mtcars, mpg, am)
# A tibble: 2 x 2
am `mean(mpg)`
<dbl> <dbl>
1 0 17.1
2 1 24.4
(dplyr_0.8.0.1)
最佳答案
如果我们想在 'my_ttest' 中分别传递参数并在函数内部构造一个公式,请将 quosure ( enquo
) 转换为 'variable' 和 'by' 的符号 ( sym
),然后构造表达式('expr1') 和 eval
吃`它
my_ttest <- function(df, variable, by, env = parent.frame()){
variable <- rlang::sym(rlang::as_label(rlang::enquo(variable)))
by <- rlang::sym(rlang::as_label(rlang::enquo(by)))
exp1 <- rlang::expr(!! variable ~ !! by)
t.test(formula = eval(exp1), data = df)
}
my_ttest(mtcars, mpg, am)
#Welch Two Sample t-test
#data: mpg by am
#t = -3.7671, df = 18.332, p-value = 0.001374
#alternative hypothesis: true difference in means is not equal to 0
#95 percent confidence interval:
# -11.280194 -3.209684
#sample estimates:
#mean in group 0 mean in group 1
# 17.14737 24.39231
或者如评论中提到的@lionel,可以直接使用
ensym
来完成my_ttest <- function(df, variable, by, env = parent.frame()){
exp1 <- expr(!!ensym(variable) ~ !!ensym(by))
t.test(formula = eval(exp1), data = df)
}
my_ttest(mtcars, mpg, am)
编辑:基于@lionel 的评论
关于R:将 t.test 包装在一个函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55317284/