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

Viewed 197

I am working with the following data set

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)
})

I wish to write a higher-order function to perform statistical tests on categorical dependet variables (such as chi square or Fisher).

As an example I am running these two tests:

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

I define my higher-order function as so:

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
             }
      )
    }

I then apply my higher order function in one block of code:

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

However, I get the following error message:

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

I suspect that my use of table() within as.formula is perhaps the cause of this? Any help would be much appreciated.

1 Answers

Vectorize solution could be

#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
Related