To create a three-way table in R, you can use ftable() function along with xtabs() function.

The following method shows how you can do it with syntax.

Method 1: Use ftable() and xtabs() Function

tab <- xtabs(~ column1 + column2 + column3, data=df)

ftable(tab)

The following example shows how to create three-way table using ftable() and xtabs() function in R.

Using ftable() and xtabs() Function

Let’s see how we can use ftable() and xtabs() function in R:

# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H"),
                 Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58),
                 Temperature=c(78,89,85,84,81,79,77,85),
                 Humidity=c(5,7,1,2,7,8,9,4),
                 Status=c("OK","Suspect","OK","OK","Suspect","Suspect","OK","Suspect"),
                 Started=c("Yes","No","Yes","Yes","No","No","Yes","No"))

# Create three-way table
three_way <- xtabs(~ Machine_name + Status + Started, data=df)

# Create compact version
ftable(three_way)

Output:

                     Started No Yes
Machine_name Status                
A            OK               0   1
             Suspect          0   0
B            OK               0   0
             Suspect          1   0
C            OK               0   1
             Suspect          0   0
D            OK               0   1
             Suspect          0   0
E            OK               0   0
             Suspect          1   0
F            OK               0   0
             Suspect          1   0
G            OK               0   1
             Suspect          0   0
H            OK               0   0
             Suspect          1   0

Here the output shows three way table created using Machine_name, Status and Started columns of dataframe.