How to Find All Unique Combinations of 2 Vectors in R Programming (Example Code)

In this R programming tutorial you’ll learn how to create a data frame containing all unique combinations of two vectors.

Creating Example Data

my_first_vector <- LETTERS[1:3]                   # Creating some vectors
my_second_vector <- 1:5

Example: Create Data Frame with Unique Combinations

expand.grid(my_first_vector, my_second_vector)    # Apply expand.grid function
#    Var1 Var2
# 1     A    1
# 2     B    1
# 3    AA    1
# 4   CDE    1
# 5     A    2
# 6     B    2
# 7    AA    2
# 8   CDE    2
# 9     A    3
# 10    B    3
# 11   AA    3
# 12  CDE    3

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top