Table Function in R


The table() function in R can be used to quickly create frequency tables. You have rows and columns of data. In one of your columns you have some data. You wonder how often each piece of data appears in the table. You can use the table function in R to see the distribution. Here we have people and their favorite colors.

In the code below we’ll first create a data frame.

df <- data.frame(person = c('Bob', 'Sally', 'Sam', 'Jill'), fav_color = c('blue', 'purple', 'blue', 'red'))
df
table(df$fav_color)

Below is what the console produces in RStudio.

> df <- data.frame(person = c('Bob', 'Sally', 'Sam', 'Jill'), fav_color = c('blue', 'purple', 'blue', 'red'))
> df
  person fav_color
1    Bob      blue
2  Sally    purple
3    Sam      blue
4   Jill       red
> table(df$fav_color)

  blue purple    red 
     2      1      1 

If we were to create a chart, it would be a histogram.

Leave a Reply