2019-06-21

Contingency tables in R

Problem

We want to create a contingency table for one or multiple variables.

Solution

  • One variable
  • table(mtcars$am)
    
     0  1 
    19 13 
    
  • Two variables
  • table(mtcars$am, mtcars$gear)
    
         3  4  5
      0 15  4  0
      1  0  8  5
    
    If we want to include the names of the variables:

    table(mtcars[, c("am", "gear")]) 
    tabla <- table(mtcars[, 9:10])
    # or the argument dnn:
    table(mtcars$am, mtcars$gear, dnn = c("am", "gear"))
    
       gear
    am   3  4  5
      0 15  4  0
      1  0  8  5
    
  • Three variables
  • table(mtcars[, c("am", "gear", "cyl")])
    
    , , cyl = 4
    
       gear
    am   3  4  5
      0  1  2  0
      1  0  6  2
    
    , , cyl = 6
    
       gear
    am   3  4  5
      0  2  2  0
      1  0  2  1
    
    , , cyl = 8
    
       gear
    am   3  4  5
      0 12  0  0
      1  0  0  2
    
  • Flat contingency tables
  • In the previous example, a better approach would be to create a flat contingency table.

    ftable(mtcars[, c("am", "gear", "cyl")])
    
            cyl  4  6  8
    am gear             
    0  3         1  2 12
       4         2  2  0
       5         0  0  0
    1  3         0  0  0
       4         6  2  0
       5         2  1  2
    
    We use the arguments row.vars and col.vars to provide the numbers or names of the variables to be used for the rows and columns of the flat contingency table. If neither of these two is given, the last variable is used for the columns. In our example the variable cyl.

    ftable(mtcars[, c("am", "gear", "cyl")], col.vars = c(1, 2))
    
         am    0        1      
        gear  3  4  5  3  4  5
    cyl                       
    4         1  2  0  0  6  2
    6         2  2  0  0  2  1
    8        12  0  0  0  0  2
    

Alternative

The function xtabs creates contingency tables using a formula interface, each variable separated by +.

# One variable
xtabs(~ am, mtcars)
# Two variables
xtabs(~ am + gear, mtcars)
# Three variables
xtabs(~ am + gear + cyl, mtcars)
# Flat contingency table
ftable(xtabs(~ am + gear + cyl, mtcars))

Related posts

No hay comentarios:

Publicar un comentario

Nube de datos