Search code examples
rcontingency

is there a way in R to specify all different three-way combinations in a contingency table?


I have many variables (5) and I want to check all interaction terms (ab on response, ac on response, etc.) on a multinomial response. something like the following where response has three levels:

multinom(response~(a+b+c+d+e)^2)

I want to create contingency tables to see if separation exists at some levels between my predictors and response. I could write something manually to get the indicator counts at each combination like so:

xtabs(~response+a+b)
xtabs(~response+a+c)
xtabs(~response+a+d)
...

but this seems cumbersome. Is there a way to output all possible three way combinations I can specify in some sort of table function with a formula input similar to the regression formula above?

Thanks,


Solution

  • Here is an example using in-built UCBasmissions dataset

    (somedata <- as.data.frame(UCBAdmissions))
    
    (collection <- setdiff(names(somedata), "Freq")) 
    
    (combinations <- combn(x = collection,
          m=2,
          simplify = FALSE))
    
    
    (all_results <- lapply(combinations, \(x){xtabs(data=somedata,
                                                    formula = as.formula(paste("~Freq",x[1],x[2],sep = " + ")))}))