expand.grid Function in R (Example)
In this article, I’ll explain how to get all combinations of two variables using the expand.grid function in the R programming language.
The article consists of one example for the application of the expand.grid function. To be more specific, the content of the page looks as follows:
Let’s do this.
Creation of Example Data
The first step is to construct some data that we can use in the example code below:
x1 <- factor(c(LETTERS[1:3])) # Create first example vector x1 # Print first example vector #  A B C # Levels: A B C
x2 <- factor(c(letters[4:7])) # Create second example vector x2 # Print second example vector #  d e f g # Levels: d e f g
The previous outputs of the RStudio console show two exemplifying factor vectors that we’ll use in the example later on.
Example: Get All Combinations Using expand.grid() Function
The following code explains how to apply the expand.grid function to return each possible combination of two factor variables.
Consider the R syntax below:
data_exp <- expand.grid(x1, x2) # Apply expand.grid function data_exp # Return output of expand.grid
Table 1 illustrates the output of the expand.grid function. By executing the previous R code, we have created a data frame object that contains one row for each possible combination of our two factor vectors.
Note that we could also insert more than two vectors within the expand.grid function in case we want to find the possible combinations between multiple vector objects.
Video & Further Resources
Do you want to learn more about the application of the expand.grid function? Then I recommend watching the following video which I have published on my YouTube channel. In the video, I demonstrate the R codes of this tutorial in a live session.
In addition, you might read some of the related tutorials on this website.
- Find Unique Combinations of All Elements from Two Vectors
- Calculate Combinations & Permutations in R
- Useful Commands in R (+ Examples)
- The R Programming Language
In this tutorial you have learned how to apply the expand.grid function in the R programming language. In case you have any additional comments and/or questions, please let me know in the comments section. Furthermore, don’t forget to subscribe to my email newsletter in order to receive updates on the newest tutorials.