# how to expand dataframe in r

Last Updated : 21 Dec, 2023

In this article, we will discuss how to expand the data frame in R Programming Language. Now create a Data Frame of all the Combinations of Vectors passed as Arguments in R Programming using expand.grid() Function.

## expand.grid() Function

`expand.grid()` function in R Programming Language is used to create a data frame with all the values that can be formed with the combinations of all the vectors or factors passed to the function as an argument.

Syntax:

expand.grid(…)

Parameters:…: Vector1, Vector2, Vector3, …

## R

 `# R program to create a dataframe ` `# with combination of vectors `   `# Creating vectors ` `x1 <- ``c``(``"abc"``, ``"cde"``, ``"def"``) ` `x2 <- ``c``(1, 2, 3) ` `x3 <- ``c``(``"M"``, ``"F"``) `   `# Calling expand.grid() Function ` `expand.grid``(x1, x2, x3) `

Output:

`   Var1 Var2 Var31   abc    1    M2   cde    1    M3   def    1    M4   abc    2    M5   cde    2    M6   def    2    M7   abc    3    M8   cde    3    M9   def    3    M10  abc    1    F11  cde    1    F12  def    1    F13  abc    2    F14  cde    2    F15  def    2    F16  abc    3    F17  cde    3    F18  def    3    F`

## R

 `# R program to create a dataframe ` `# with combination of vectors `   `# Creating vectors ` `x1 <- ``c``(``"abc"``, ``"cde"``, ``"def"``) ` `x2 <- ``c``(1, 2, 3) ` `x3 <- ``c``(``"M"``, ``"F"``) `   `# Calling expand.grid() Function ` `expand.grid``(x1, x3) `

Output:

`   Var1 Var21  abc    M2  cde    M3  def    M4  abc    F5  cde    F6  def    F`

## R

 `# Mixed data types` `letters` `<- ``c``(``"A"``, ``"B"``, ``"C"``)` `numbers <- ``c``(1, 2, 3)` `logicals <- ``c``(``TRUE``, ``FALSE``)`   `# Create combinations` `result_df <- ``expand.grid``(Letter = ``letters``, Number = numbers, Logical = logicals)`   `# Display the result` `print``(result_df)`

Output:

`   Letter Number Logical1       A      1    TRUE2       B      1    TRUE3       C      1    TRUE4       A      2    TRUE5       B      2    TRUE6       C      2    TRUE7       A      3    TRUE8       B      3    TRUE9       C      3    TRUE10      A      1   FALSE11      B      1   FALSE12      C      1   FALSE13      A      2   FALSE14      B      2   FALSE15      C      2   FALSE16      A      3   FALSE17      B      3   FALSE18      C      3   FALSE`