Generalizable for loop for all possible 2-way tables?

47 Views Asked by At

I'm sure the answer is staring me in the face here so bear with me but how do I build a for loop that iterates through a dataframe, creating 2-way contingency tables for all possible iterations?

Sample dataframe:

amazon <- c(0,1,0,1,1)
age <- c(1,2,4,3,0)
income <- c(1,1,1,0,0)
delivery <- c(1,2,0,3,4)
manhattan <- c("Manhattan", "Other", "Manhattan", "Other", "Manhattan")

df <- data.frame(cbind(amazon, age, income, delivery, manhattan))
df <- df %>% mutate(across(everything(), as.factor))

So all columns are categorical/binary variables classed as factors

I've tried

results <- data.frame()

for(i in 1:(ncol(df))){
  for(j in (i+1):ncol(df)){
    table <- table(df[,i], df[,j], useNA = "ifany")
    results <- rbind(results,ftable(round(prop.table(table),3)))
  }
}

I've also tried this:

make_p_tab <- function(x) {
  col_df <- df %>% dplyr::select(var1, all_of(x)) %>% filter(!is.na(x)) %>%
  table() %>% prop.table(.,1)
}

to_do <- function(df){
  colnames(df)
}

food_xtab <- map(to_do, make_p_tab)

And was expecting multiple contingency tables so the output would look as if I'd written out each contingency table one by one.

table(df$amazon, df$age)
table(df$amazon, df$income)
table(df$amazon, df$manhattan)...
table(df$delivery, df$manhattan)

thank you!

1

There are 1 best solutions below

2
Onyambu On

Directly use combn:

combn(df, 2, table, simplify = FALSE)

[[1]]
      age
amazon 0 1 2 3 4
     0 0 1 0 0 1
     1 1 0 1 1 0

[[2]]
      income
amazon 0 1
     0 0 2
     1 2 1

[[3]]
      delivery
amazon 0 1 2 3 4
     0 1 1 0 0 0
     1 0 0 1 1 1

[[4]]
      manhattan
amazon Manhattan Other
     0         2     0
     1         1     2

  :
  :
  :