Table Function in R – Frequency table in R & cross table in R

Table function in R -table(), performs categorical tabulation of data with the variable and its frequency. Table() function is also helpful in creating Frequency tables with condition and cross tabulations.

Lets see usage of R table() function with some examples

Frequency table with table function in R :

Main Objective of table function in R is creating Frequency table. Lets use iris data set to demonstrate our example. Lets create a frequency table for types of species in iris.

## Frequency table with table() function in R

table(iris$Species)

when we execute the above code, the output will be

table function in R 1 frequency table in r
Which says that there are 50 observation in each species (setosa, versicolor & virginica)

 

Frequency table with condition:

We can also create a frequency table with predefined condition using R table() function.For example lets say we need to get how many obervations have Sepal.Length>5.0 in iris table.

## Frequency table with condition using table function in R

table(iris$Sepal.Length>5.0)

when we execute the above code the output will be

FALSE    TRUE

32           118

Which says there are

  • 118 observation with Sepal.Length >5.0
  •  32 observation with Sepal.Length <=5.0

 

2 way cross table in R:

Table function also helpful in creating 2 way cross table in R. For example lets say we need to create cross tabulation of gears and carb in mtcars table

## cross tabulation gear * carb 

table(mtcars$gear,mtcars$carb)

when we execute the above code the output will be

table function in R

Which says there are 3 cars which has carb=1 and gear=3 and so on.

 

3 way cross table in R:

Similar to 2 way cross table we can create a 3 way cross table in R with the help of table function.

## 3 way cross tabulation gear * carb* cyl with table function in R

table(mtcars$gear,mtcars$carb,mtcars$cyl)

when we execute the above code the output will be

table function in R 3 cross table 3 way

Indirectly it gives the cross tabulation of gear* carb  for cyl=4,cyl=6 and cyl=8 separately as shown above.

 

previous small table function in r                                                                                                                next small table function in r