Error: Quosures can only be unquoted within a quasiquotation context

Error: Quosures can only be unquoted within a quasiquotation context

我正在设置一个函数,以便更轻松地同时在多个列上 运行 weights:wtd。chi.sq。

这是我的示例数据:

library(weights) 

 data_in <- read_table2("Q50_1   Q50_2   Q38 Q90 pov gender  wgt1 wgt2
never   always   Yes 2   High    M   1.3 0.4
sometimes   always   No  2   Med F   0.4 0.2
always   sometimes   Yes 4   Low F   1.2 0.7
never   never   No  2   High    M   0.5 0.7
always   always   No  4   High    M   0.7 0.8
sometimes   never   Yes 3   Low F   0.56 0.3
sometimes   never   Yes 2   Med F   0.9 0.1
")

我将使用此行通过 pov:

查找 Q50_1 的卡方值
wtd.chi.sq(data_in$Q50_1,data_in$pov, weight = data_in$wgt1)
    Chisq        df   p.value 
7.3395092 4.0000000 0.1189981

由于我需要为具有数千个变量的 df 重复此操作,因此我设置了一个函数来 运行 它。 wtd.chi.sq 采用向量,而不是列名,因此将相关列输入其中有点棘手。我编写的函数如下所示:

xtab_func <- function(dat, col, target, wgt){
  col <- sym(col)
  target <- enquo(target)
  wgt <- enquo(wgt)
  weights::wtd.chi.sq(noquote(paste0(dat,"$",!!target)), noquote(paste0(dat,"$",!!col)), weight = noquote(paste0(dat,"$",!!wgt)))
}

但是当我运行它时:
xtab_func('dat', 'Q50_1','pov','wgt1')

 Error: Quosures can only be unquoted within a quasiquotation context.

  # Bad:
  list(!!myquosure)

  # Good:
  dplyr::mutate(data, !!myquosure)
Run `rlang::last_error()` to see where the error occurred. 

谁能告诉我这是怎么回事?!

使用 ensym 可能更好,因为我们可以传递带引号或不带引号的输入。然后用as_string把符号转成字符串,然后我们用base RExtract的方法([[)提取列作为向量,用在[=17] =]

xtab_func <- function(dat, col, target, wgt){
  col <- rlang::as_string(ensym(col))
  target <- rlang::as_string(ensym(target))
  wgt <- rlang::as_string(ensym(wgt))
   wtd.chi.sq(dat[[target]],dat[[col]], weight = dat[[wgt]])

}

-测试

xtab_func(data_in, 'Q50_1','pov','wgt1')
 Chisq        df   p.value 
7.3395092 4.0000000 0.1189981 
xtab_func(data_in, Q50_1, pov, wgt1)
    Chisq        df   p.value 
7.3395092 4.0000000 0.1189981 

注意:传入函数的数据集未被引用