How to Get the Cartesian Product in R (Example Code)

This tutorial demonstrates how to get the cartesian product in the R programming language.

Constructing Example Data

A <- LETTERS[1:3]                     # Create example data
A
# [1] "A" "B" "C"
B <- letters[1:3]
B
# [1] "a" "b" "c"

Example: Apply expand.grid() Function to Return Cartesian Product

expand.grid(A, B)                     # Get cartesian product
#   Var1 Var2
# 1    A    a
# 2    B    a
# 3    C    a
# 4    A    b
# 5    B    b
# 6    C    b
# 7    A    c
# 8    B    c
# 9    C    c

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