Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Wrapping t.test in a function

Tags:

r

dplyr

tidyeval

Why does this function fail to execute?

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

But this one works

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)

like image 258
Sasha Avatar asked Sep 17 '25 08:09

Sasha


1 Answers

If we want to pass the arguments separately in 'my_ttest' and construct a formula inside the function, convert the quosure (enquo) to a symbol (sym) for both 'variable', 'by', then construct the expression ('expr1') and evaluate` it

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 

Or as @lionel mentioned in the comments, it can be done directly with 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)

EDIT: Based on @lionel's comments

like image 129
akrun Avatar answered Sep 21 '25 14:09

akrun