What is the expand.grid() function in R?

Overview

The expand.grid() function in R is used to return a data frame from all combinations of the vector or factor objects supplied to it.

Syntax

expand.grid(...)
Syntax for the expand.grid() function

Parameter

This function takes the ... as a parameter value. It indicates the vectors, factors, or a list containing these.

Return value

The expand.grid() function returns a data frame that contains a row for each combination of the supplied vectors or factors.

Example

Let's look at the code below:

#creating factor objects
a <- c( 1, 2, 3)
b <- c( 4, 5, 6)
c <- c( 7, 8, 9)
# implementing the expand.grid() function
expand.grid(a, b, c)

Explanation

  • Lines 2 to 4: We create factor objects, a, b and c.
  • Line 7: We call the expand.grid() function and pass the factor objects as its arguments. We obtain and print the result to the console.

Free Resources