# Test If Two Grouping Factors Have Same Groups in R (Example)

This tutorial demonstrates how to **compare the groups of two factor vectors** in R programming.

The table of content is structured as follows:

Letâ€™s dive into it!

## Creation of Example Data

The first step is to create some data that we can use in the following examples:

x1 <- factor(c("a", "b", "a", "b", "b")) # Create first factor vector x1 # Print first factor vector # [1] a b a b b # Levels: a b

x2 <- factor(c("c", "d", "c", "d", "d")) # Create second factor vector x2 # Print second factor vector # [1] c d c d d # Levels: c d

x3 <- factor(c("c", "d", "c", "a", "a")) # Create third factor vector x3 # Print third factor vector # [1] c d c a a # Levels: a c d

The previous outputs of the RStudio console show the structure of our example data: We have created three factor vectors with different factor levels.

Even though the levels of our factors are different, the groupings may be the same (i.e. the groups are just called differently). Letâ€™s test this!

## Example: Checks If Two Grouping Factors Contain Same Groups Using all_groups_identical() Function of groupdata2 Package

In this example, Iâ€™ll illustrate how to test whether the groupings of two factor objects are the same.

First, we have to install and load the groupdata2 package:

install.packages("groupdata2") # Install & load groupdata2 library("groupdata2")

In the next step, we can apply the all_groups_identical function. First, letâ€™s check whether the groupings of the first and second vector are equal to each other:

all_groups_identical(x1, x2) # Check groupings of first & second # [1] TRUE

The RStudio console returns the logical indicator TRUE, i.e. the two vectors have the same groupings.

Letâ€™s apply the all_groups_identical function once again to compare the first and third vectors:

all_groups_identical(x1, x3) # Check groupings of first & third # [1] FALSE

The RStudio console returns FALSE, i.e. the vectors x1 and x3 have different groups.

## Video & Further Resources

Have a look at the following video instruction on the Statistics Globe YouTube channel. Iâ€™m showing the topics of this tutorial in the video:

Furthermore, you might have a look at the related R posts on this homepage.

- Compare Vectors and Find Differences
- Two Functions with Same Name in Different Packages
- Check If Two Data Frames are the Same
- All R Programming Examples

This article has demonstrated how to **test if two grouping factors contain identical groups** in the R programming language. Donâ€™t hesitate to let me know in the comments section, in case you have further questions.