To create a frequency table of multiple variables in R, you can use table() function and summarise() function from dplyr package.
The following methods show how you can do it with syntax.
Method 1: Use table() Function
table(df$column1, df$column2)
Method 2: Use dplyr Package
library(dplyr)
df %>%
group_by(df$column1, df$column2) %>%
summarise(count = n())
The following examples show how to create frequency table of multiple variables in R.
Create Frequency Table of Multiple Variables Using table() Function in R
Let’s see how we can use table() function 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$Machine_name, df$Status)
# Print frequency table
print(f)
Output:
OK Suspect
A 3 0
B 1 2
C 2 0
D 1 1
E 0 2
F 0 1
G 0 1
H 2 0
Here the output shows frequency table for Machine_name and Status column of data frame.
Create Frequency Table of Multiple Variables Using dplyr Package in R
Let’s see how we can use function from 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
f <- df %>%
group_by(df$Machine_name, df$Status) %>%
summarise(count = n())
# Print frequency table
print(f)
Output:
`df$Machine_name` `df$Status` count
<chr> <chr> <int>
1 A OK 3
2 B OK 1
3 B Suspect 2
4 C OK 2
5 D OK 1
6 D Suspect 1
7 E Suspect 2
8 F Suspect 1
9 G Suspect 1
10 H OK 2
Here the output shows frequency table for Machine_name and Status column of data frame.