R:在函数中包装 t.test

R: Wrapping t.test in a function

为什么这个函数执行失败?

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)

并非每个函数(和包)都适用于 tidy 求值。 t.test 将数值向量 x,y 作为参数或公式。在您的示例中,您可以提供公式和数据框,但实际上它似乎并不比直接调用 t.test 更有效。


my_ttest <- function(df, frma) {
  t.test(frma, 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

reprex package (v0.2.1)

于 2019-03-23 创建

如果我们想在'my_ttest'中单独传递参数并在函数内部构造一个公式,将quosure(enquo)转换为符号(sym)对于两个'variable', 'by', 然后构造表达式 ('expr1') 并 evaluate` 它

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 的评论