创建对 `mice::with.mids()` 的调用

Create a call to `mice::with.mids()`

我正在尝试创建对 mice::with.mids() 的调用,然后对其求值。似乎正在创建调用,但无法对其进行评估(一定是 environment/scoping 问题?)。我在下面创建了一个简化的可重现示例。非常感谢任何帮助!谢谢!

mice_in_tbl_uvregression <- 
  function(data,   # mice data of class mids
           method, # regression method, eg. lm, glm
           formula = "hp ~ mpg", # character formula (needs to be character for other reasons)
           method.args = NULL # named list of other args that will be passed to `method=`
  ) {
    # construct the call
    fun_call <-
      rlang::call2(
        rlang::expr(with),
        data = data,
        expr = rlang::expr((!!method)(formula = !!as.formula(formula), !!!method.args))
      )
    
    # evaluate call
    eval(fun_call)
  }

set.seed(12345)
mice_in_tbl_uvregression(
  data = mice::mice(mtcars, m = 2),
  method = lm
)
#> Error in eval(predvars, data, env): object 'hp' not found

reprex package (v2.0.0)

于 2021-06-27 创建

我们可以 parse 在执行 eval 计算

之前创建一个字符串(以提取 language 调用)
mice_in_tbl_uvregression <- 
  function(data,   # mice data of class mids
           method, # regression method, eg. lm, glm
           formula = "hp ~ mpg", # character formula (needs to be character for other reasons)
           method.args = NULL # named list of other args that will be passed to `method=`
  ) {
    # construct the call
   
    fun_call <- parse(text = glue::glue("with(data = {deparse(substitute(data))}, expr = {deparse(substitute(method))}(as.formula({formula})))"))
    print(fun_call[[1]])
    out <- eval(fun_call)
    out$call$expr[[2]] <- out$call$expr[[2]][[2]]
   out
    
  }

-测试

set.seed(12345)
out1 <- mice_in_tbl_uvregression(
  data = mice::mice(mtcars, m = 2),
  method = lm
)

-输出

 out1
call :
with.mids(data = mice::mice(mtcars, m = 2), expr = lm(hp ~ mpg))

call1 :
mice::mice(data = mtcars, m = 2)

nmis :
 mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
   0    0    0    0    0    0    0    0    0    0    0 

analyses :
[[1]]

Call:
lm(formula = as.formula(hp ~ mpg))

Coefficients:
(Intercept)          mpg  
     324.08        -8.83  


[[2]]

Call:
lm(formula = as.formula(hp ~ mpg))

Coefficients:
(Intercept)          mpg  
     324.08        -8.83