Joe
Joe

Reputation: 3806

Calling a formula within a custom function using quosures

I am trying to run a t-test within a custom function, and am running into a quosure misapplication (I believe). Any help would be greatly appreciated.

library(tidyverse) 

tp_pull <- function(mydata, dv, iv){
  dv <- enquo(dv)
  iv <- enquo(iv)
  t.test(!!dv ~ !!iv, mydata) 
}

tp_pull(mydata = mtcars, dv = mpg, iv = vs) 

My error message reads:

numerical expression has 2 elements: only the first usedNAs introduced by 
coercion
Show Traceback
Error in quo_name(dv):~!(!iv) : NA/NaN argument

For context this t-test will be part of a larger custom function.

Upvotes: 2

Views: 295

Answers (1)

MrFlick
MrFlick

Reputation: 206253

Quosures are unique to tidyeval and are not supposed by the base R language. Right now they only work with dplyr. It is very unlikely these will ever work with base functions such as t.test.

If you want to do this with base R, you can use G. Grothendieck's suggestion of

tp_pull <- function(mydata, dv, iv){
  t.test(formula(substitute(dv ~ iv)), mydata)
}

tp_pull(mydata = mtcars, dv = mpg, iv = vs) 

The substitute captures the un-evaulated symbol names from the promise passed to the call and allows you to re-assemble them into a new expression. The formula() call helps coerce the un-evaulated expression returned by substitute() into a proper R formula object.

Upvotes: 4

Related Questions