Non-Redundant Version of expand.grid in R (Example)

 

In this R post you’ll learn how to get the output of the expand.grid function without duplicates.

The article contains the following content:

Let’s dive right in:

 

Creation of Example Data

Have a look at the following example data:

x <- LETTERS[1:3]                 # Create example vector
x                                 # Print example vector
# [1] "A" "B" "C"

As you can see based on the previous output of the RStudio console, our example data is a character vector containing three different elements.

Let’s assume that we want to find all combinations of the elements in this vector. Then, we might apply the expand.grid function as shown below:

data_expg <- expand.grid(x, x)    # Apply expand grid
data_expg                         # Grid with duplicates

 

table 1 data frame non redundant version expand grid r

 

So far, so good! However, the expand.grid function returns duplicates (i.e. “A B” and “B A”) as well as the same element twice (i.e. “A A”).

The following example shows how to avoid such redundant outputs…

 

Example: Create Non-Redundant Version of expand.grid() Using combn() Function

This example illustrates an alternative to the expand.grid function in case you want to get an output without duplicates.

For this task, we can apply the combn function. Within the combn function, we have to specify the name of our vector (i.e. x) as well as the number of values to combine (i.e. 2).

data_combn <- combn(x, 2)         # Apply combn
data_combn                        # Grid without duplicates

 

table 2 matrix non redundant version expand grid r

 

After running the previous R programming code the matrix shown in Table 2 has been created.

As you can see, this matrix contains all combinations without showing any duplicates.

 

Video & Further Resources

Would you like to learn more about the printing of the output of the expand.grid function without duplicates? Then you may have a look at the following video on my YouTube channel. I’m explaining the content of this post in the video.

 

The YouTube video will be added soon.

 

In addition, you may want to read some of the other articles on this website. I have published several tutorials already.

 

In summary: In this R tutorial you have learned how to return the output of the expand.grid function without duplicates.

In this specific tutorial, I have illustrated how to do that based on a character string. However, please note that we could also use other input data such as numeric or integer values.

Please let me know in the comments, if you have further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top