Here is a short guide to producing Cartesian Products in R. Cartesian products is a concept from the mathematical field of set theory. To create Cartesian products at least two sets are required. Those from a computer science background would be more familiar with arrays (vectors) more than sets.

A related post to this would be one of my old pages: An Introduction To Set Theory & Logic (Part Three Of Three)

**Table Of Contents**

**Cartesian Products**

The Cartesian product of sets and is denoted by or “A cross B”. It is the set of all ordered pairs (a, b) such that and or . You can also think of the Cartesian products as all possible combinations between two sets.

If we have then that can be written as .

If either set or set (or both of them) is empty () then the Cartesian product would be empty as well. ()

In the Cartesian product, we can determine the number of elements in this set. Denote as the number of elements in the set A and denote as the number of elements in the set B. If sets and are sets with a finite number of elements then .

**An Example Of A Cartesian Product **

Here is an example of how the Cartesian product operates.

Suppose we have the set and the set . What is the Cartesian product ? What about and ?

__Answer__

The Cartesian products here are all possible combinations between the two sets.

From the sets P and Q we can find the number of elements in the Cartesian products. The sets , contain elements each and has elements.

**Examples of Cartesian Products in R**

In the statistical program R, there is a built in function which can produce Cartesian products from at least two sets/vectors. This expand.grid() function is the R version of Cartesian products.

The first example in R is the example from the previous section. Note that the output in R has a different order from the answers above.

This second example is somewhat more practical in the sense that the Cartesian product helps in finding all possible combinations between the fruits set and the animals set.

If you want to change the column titles from Var1 and Var2, you can use the following line of code in R:

1 |
colnames( <table_name> ) <- c("col1_title", "col2_title") |

**Reference**

Source: http://stackoverflow.com/questions/4309217/cartesian-product-data-frame-in-r