代码之家  ›  专栏  ›  技术社区  ›  ykl

as中的表()。在R函数中使用paste()的formula()

  •  2
  • ykl  · 技术社区  · 7 年前

    我正在使用以下数据集

    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
    

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

    表中出错(schtyp,女性):未找到对象“schtyp”

    我怀疑我在as中使用了table()。公式可能是原因?任何帮助都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Prem    7 年前

    矢量化解决方案可以是

    #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