Working with Tables
In R, tables are used to summarize categorical data and count occurrences of values.
Creation of Table:
To create a table in R, use the table() function. And it has arguments as vectors.
Syntax:
table(data, ...)
Example:
> # Working with single vector
> # vector
> gender <- c("Male", "Female", "Male", "Female", "Male", "Male")
> # table creation
> tbl_gender <- table(gender)
> print(tbl_gender)
gender
Female Male
2 4
Note: The function returns a frequency table for each unique value in a vector.
Example:
> # Working with two vectors
> # vector 1
> gender <- c("Male", "Female", "Male", "Female", "Male", "Male")
> # vector 2
> department <- c("HR", "IT", "HR", "IT", "Finance", "Finance")
> # table creation
> tbl_emp <- table(department, gender)
> print(tbl_emp)
gender
department Female Male
Finance 0 2
HR 0 2
IT 2 0
Note: This creates a cross-tabulation of department and gender. This is also called as Two-Way Table (Contingency Table).