Create a Data Frame of all the Combinations of Vectors passed as Argument in R Programming – expand.grid() Function

expand.grid() function in R 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 argument.

Syntax: expand.grid(…)

Parameters:
…: Vector1, Vector2, Vector3, …

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

   Var1 Var2 Var3
1   abc    1    M
2   cde    1    M
3   def    1    M
4   abc    2    M
5   cde    2    M
6   def    2    M
7   abc    3    M
8   cde    3    M
9   def    3    M
10  abc    1    F
11  cde    1    F
12  def    1    F
13  abc    2    F
14  cde    2    F
15  def    2    F
16  abc    3    F
17  cde    3    F
18  def    3    F

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

  Var1 Var2
1  abc    M
2  cde    M
3  def    M
4  abc    F
5  cde    F
6  def    F
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.