我正在设置一个函数,以便更轻松地同时在多个列上运行 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 的 chi sq 值:
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.
谁能告诉我这里发生了什么?!