Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

r - passing formula in a list to `rlang::exec`

I am trying to use rlang::exec in custom functions where I want to pass additional arguments as a list and then splice them. Usually this works without any problem. But I am encountering problems while doing this routine when there is a formula argument involved.

without list

library(rlang)

exec(
  .fn = stats::t.test,
  formula = wt ~ am,
  data = mtcars
)
#> 
#>  Welch Two Sample t-test
#> 
#> data:  wt by am
#> t = 5.4939, df = 29.234, p-value = 6.272e-06
#> alternative hypothesis: true difference in means between group 0 and group 1 is not equal to 0
#> 95 percent confidence interval:
#>  0.8525632 1.8632262
#> sample estimates:
#> mean in group 0 mean in group 1 
#>        3.768895        2.411000

with list


extra.args <- list(formula = wt ~ am) 

exec(
  .fn = stats::t.test,
  data = mtcars,
  !!!extra.args
)
#> Error in t.test.default(data = structure(list(mpg = c(21, 21, 22.8, 21.4, : argument "x" is missing, with no default

How can I get this to work?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure this is rlang::exec's fault. The problem really has to do with S3 dispatch and the fact that different functions are called based on the class of the first parameter, not the names of the parameters. With your current calling method, you are passing data= before your formula. This also causes a problem when calling the function directly

stats::t.test(data=mtcars, formula=wt~am)

The easiest way to get around this would be to pass the parameters in the "natural" order for proper S3 dispatch to take place

extra.args <- list(formula = wt ~ am) 
exec(
  .fn = stats::t.test,
  !!!extra.args,
  data = mtcars
)

or leave the formula parameter unnamed so it becomes the first unnamed-parameter.

extra.args <- list(wt ~ am) 

exec(
  .fn = stats::t.test,
  data = mtcars,
  !!!extra.args
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...