R:将t.test包装在函数中

时间:2019-03-23 18:54:22

标签: r dplyr tidyeval

为什么此功能无法执行?

my_ttest <- function(df, variable, by){
    variable <- enquo(variable)
    by <- enquo(by)

    t.test(!!variable ~ !!by, df)
}
  

my_ttest(mtcars,mpg,上午)       is_quosure(e2)中的错误:参数“ e2”丢失,没有默认值

但是这个有效

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)

2 个答案:

答案 0 :(得分:2)

并非每个函数(和程序包)都可以进行整洁的评估。 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创建

答案 1 :(得分:2)

如果我们想分别在'my_ttest'中传递参数并在函数内部构造一个公式,则将'variable',''的quosure(enquo)转换为符号(sym)。 by”,然后构造表达式('expr1')并对其进行eval uate

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