table() 在 as.formula() 中使用 R 函数中的 paste()

table() within as.formula() using paste() in R function

我正在处理以下数据集

hsb2 <- within(read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv"), {
  race <- as.factor(race)
  schtyp <- as.factor(schtyp)
  prog <- as.factor(prog)
})

我希望编写一个高阶函数来对分类因变量(例如卡方或 Fisher)执行统计检验。

举个例子我是运行这两个测试:

chisq.test(table(hsb2$female, hsb2$schtyp))
chisq.test(table(hsb2$race, hsb2$schtyp))

我这样定义我的高阶函数:

multi.tests.categorical <- function(fun = chisq.test, df, vars, group.var, ...) {
      sapply(simplify = FALSE,                                    
             vars,                                                
             function(var) {
               formula <- as.formula(paste("table(",var, ",", group.var,")")) # create a formula with outcome and grouping var.
               fun(data = df, formula, ...)                     # perform test with a given fun, default t.test
             }
      )
    }

然后我在一个代码块中应用我的高阶函数:

res.multi.chisq.tests <-
  multi.tests.categorical(fun = chisq.test,
              df = hsb2,
              vars = "schtyp",
              group.var = c("female","race"))
res.multi.chisq.tests

但是,我收到以下错误消息:

Error in table(schtyp, female) : object 'schtyp' not found

我怀疑我在 as.formula 中使用 table() 可能是这个原因?任何帮助将不胜感激。

向量化解决方案可以是

#sample data
hsb2 <- within(read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv"), {
  race <- as.factor(race)
  schtyp <- as.factor(schtyp)
  prog <- as.factor(prog)
})

schtyp_idx <- match("schtyp", colnames(hsb2))
col_idx <- match(c("female", "race"), colnames(hsb2))
chisq.test_resultList = mapply(function(x,y){chisq.test(table(hsb2[,x],hsb2[,y]))}, schtyp_idx, col_idx)
chisq.test_resultList