R table() Function

The table() function in R is used to create contingency tables or frequency tables of the counts of the unique elements in a vector or array or for the combinations of two or more factors.

Syntax

 table(obj)

Parameters

  1. obj: The obj is the object to be converted to tabular form.

Diagram

table in r diagram

  1. The table can also represent tabular data based on conditions. 
  2. It can also be used for cross-tabulations.
  3. A frequency table with proportions can be created using a prop.table().
  4. Data with a table can also be represented in three-dimensional form.

    Example 1: Creating a table from a single vector

    Let’s say you have a vector and you want to create a frequency table of its elements:

    vec <- c("A", "B", "A", "C", "B", "A")
    
    table(vec)
    

    Output

    vec
    A  B  C
    3  2  1
    

    Example 2: Multiple vectors

    You can also create a cross-tabulation of two or more vectors:

    vec1 <- c("A", "B", "A", "C")
    vec2 <- c("X", "X", "Y", "Y")
    
    table(vec1, vec2)

    Output

      vec2
    vec1  X   Y
     A    1   1
     B    1   0
     C    0   1
    

    Example 3: Creating a table from a data frame

    Consider the situation where an event manager has to have a reference for the gender of their guests.

    guestList <- data.frame(
     "Name" = c("Sam", "Julie", "Rob"),
     "Gender" = c("Male", "Female", "Male")
    )
    guestListTable <- table(guestList)
    guestListTable

    Output

    Gender
    
    Name  Female  Male
    Julie   1     0
    Rob     0     1
    Sam     0     1

    Example 4: Creating a table from the dataset

    library(datasets)
    mtcars
    cylinder <- table(mtcars$cyl)
    cylinder

    Output

    example Output

    That’s it!

    Leave a Comment