To create a frequency table in R, you can use two different methods: the table()
function and the dplyr
package.
In this article, we will explore how to create frequency tables in R using these methods with examples.
Method 1: Use table() Function
The table()
function in R is used to create a frequency table. Here’s the syntax:
table(vector)
The following example shows how to create a frequency table using the table()
function:
Create Frequency Table Using table() Function
Let’s see how we can use the table()
function to create a frequency table in R:
# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H","A","B","A","C","D","B","E","H"),
Pressure=c(12.39,11.25,12.15,13.48,13.78,9.63,12.21,12.58,9.6,8.85,7.89,8.50,12.36,11.45,9.47,8.12),
Status=c("OK","Suspect","OK","OK","Suspect","Suspect","Suspect","OK","OK","OK","OK","OK","Suspect","Suspect","Suspect","OK"))
# Create frequency table
f <- table(df$Status)
# Show frequency table
print(f)
Output: 👇️
OK Suspect
9 7
Here the output shows the frequency table for the Status
column of the data frame.
Method 2: Use dplyr Package
The dplyr
package in R provides a powerful set of tools for data manipulation, including creating frequency tables. Here’s the syntax:
library(dplyr)
result <- df %>%
group_by(column_name) %>%
summarise(count = n())
The following example shows how to create a frequency table using the dplyr
package:
Create Frequency Table Using dplyr Package
Let’s see how we can use the dplyr
package in R to create a frequency table:
# Load dplyr package
library(dplyr)
# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H","A","B","A","C","D","B","E","H"),
Pressure=c(12.39,11.25,12.15,13.48,13.78,9.63,12.21,12.58,9.6,8.85,7.89,8.50,12.36,11.45,9.47,8.12),
Status=c("OK","Suspect","OK","OK","Suspect","Suspect","Suspect","OK","OK","OK","OK","OK","Suspect","Suspect","Suspect","OK"))
# Create frequency table
freq_table <- df %>%
group_by(Status) %>%
summarise(count = n())
# Display frequency table
print(freq_table)
Output: 👇️
# A tibble: 2 × 2
Status count
<chr> <int>
1 OK 9
2 Suspect 7
In this example, the dplyr
package is used to group the data by the Status
column and then summarize the count of each unique value.