how to expand dataframe in r
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 Programme to expand dataframe in R
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 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
R Programme to expand dataframe in R
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 Var2
1 abc M
2 cde M
3 def M
4 abc F
5 cde F
6 def F
R Programme to expand dataframe in R for Mixed Data Types
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 Logical
1 A 1 TRUE
2 B 1 TRUE
3 C 1 TRUE
4 A 2 TRUE
5 B 2 TRUE
6 C 2 TRUE
7 A 3 TRUE
8 B 3 TRUE
9 C 3 TRUE
10 A 1 FALSE
11 B 1 FALSE
12 C 1 FALSE
13 A 2 FALSE
14 B 2 FALSE
15 C 2 FALSE
16 A 3 FALSE
17 B 3 FALSE
18 C 3 FALSE