Search code examples
rcrosstab

freq table for multiple variables in r


I would like to crosstab the items variable vs cat as a frequency table.

df1 <- data.frame(cat =   c(1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4),
                  item1 = c(0,0,1,0,1,1,0,0,0,1,0,1,0,0,1,0,0,1),
                  item2 = c(1,1,0,1,0,1,1,0,0,0,1,0,1,1,0,0,1,0),
                  item3 = c(0,0,1,0,1,0,0,0,1,0,1,1,1,0,0,1,0,1))

> table(df1$cat, df1$item1)
   
    0 1
  1 3 1
  2 3 2
  3 3 2
  4 2 2

Is there a way to print all the items variables freq table by cat together?

Thanks


Solution

  • You can try this:

    List <- list()
    for(i in 2:dim(df1)[2])
    {
      List[[i-1]] <- table(df1$cat, df1[,i])
    }
    
    [[1]]
       
        0 1
      1 3 1
      2 3 2
      3 3 2
      4 2 2
    
    [[2]]
       
        0 1
      1 1 3
      2 3 2
      3 2 3
      4 3 1
    
    [[3]]
       
        0 1
      1 3 1
      2 3 2
      3 2 3
      4 2 2