Non-Redundant Version of expand.grid in R (Example)
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 #  "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
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
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.
In addition, you may want to read some of the other articles on this website. I have published several tutorials already.
- Find Unique Combinations of All Elements from Two Vectors
- Calculate Combinations & Permutations in R
- Fuzzy Matching in R
- R Programming Tutorials
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.