# How to Use expand.grid() Function in R

You can use the expand.grid function from base R to create a data frame of all combinations of values from specific vectors.

The following examples show how to use this function in two different scenarios:

• Scenario 1: Create Data Frame Using expand.grid with 2 Vectors
• Scenario 2: Create Data Frame Using expand.grid with 3 Vectors

Let’s jump in!

## Example 1: Create Data Frame Using expand.grid with 2 Vectors

The following code shows how to use the expand.grid() function to create a data frame that contains all combinations of values from two vectors:

#specify vectors
team <- c('A', 'B', 'C')
position <- c('Guard', 'Forward', 'Center')

#create data frame of all combinations of team and position
df <- expand.grid(team, position)

#view data frame
df

Var1    Var2
1    A   Guard
2    B   Guard
3    C   Guard
4    A Forward
5    B Forward
6    C Forward
7    A  Center
8    B  Center
9    C  Center

The resulting data frame contains all combinations of values from the team and position vectors.

For example, the value ‘A’ from the team vector has been combined with all three values from the position column.

Similarly, the value ‘B’ from the team vector has been combined with all three values from the position column.

And so on.

By default, the expand.grid function assigns column names Var1, Var2, etc. to the data frame.

If you’d like, you can use the names function to quickly rename the column names of the data frame:

#rename data frame columns
names(df) <- c('team', 'position')

#view updated data frame
df

team position
1    A    Guard
2    B    Guard
3    C    Guard
4    A  Forward
5    B  Forward
6    C  Forward
7    A   Center
8    B   Center
9    C   Center

## Example 2: Create Data Frame Using expand.grid with 3 Vectors

The following code shows how to use the expand.grid() function to create a data frame that contains all combinations of values from three vectors:

#specify vectors
team <- c('A', 'B', 'C')
position <- c('Guard', 'Forward', 'Center')
priority <- c('starter', 'backup')

#create data frame of all combinations of team, position and priority vectors
df <- expand.grid(team, position, priority)

#view data frame
df

Var1    Var2    Var3
1     A   Guard starter
2     B   Guard starter
3     C   Guard starter
4     A Forward starter
5     B Forward starter
6     C Forward starter
7     A  Center starter
8     B  Center starter
9     C  Center starter
10    A   Guard  backup
11    B   Guard  backup
12    C   Guard  backup
13    A Forward  backup
14    B Forward  backup
15    C Forward  backup
16    A  Center  backup
17    B  Center  backup
18    C  Center  backup

The resulting data frame contains all combinations of values from the team, position and priority vectors.

## Additional Resources

The following tutorials explain how to perform other common tasks in R: