Create All Possible Combinations of Selected Variables (3/3): Expand from Vectors with expand_grid()

Similar to expand() covered in the last two sections, expand_grid() also generates combinations but based on levels of vectors as input, instead of a dataset. It is very similar to the base R function expand.grid(), but with output carrying attributes of a tibble dataset, and can expand over any generalized vectors, such as data frames and matrices, as shown below.

library(tidyr)expand_grid(x = 1:3, y = 1:2)

Output:

# A tibble: 6 × 2
x y
<int> <int>
1 1 1
2 1 2
3 2 1
4 2 2
5 3 1
6 3 2
expand_grid(x = c("a", "b", "c"), y = c("A", "B", "C"))

Output:

# A tibble: 9 × 2
x y
<chr> <chr>
1 a A
2 a B
3 a C
4 b A
5 b B
6 b C
7 c A
8 c B
9 c C

You can use expand_grid() to expand data frames.

# expand data framesexpand_grid(tibble(x = 1:2, y = c("a", "b")), z = 1:3)

Output:

# A tibble: 6 × 3
x y z
<int> <chr> <int>
1 1 a 1
2 1 a 2
3 1 a 3
4 2 b 1
5 2 b 2
6 2 b 3

This can be equivalently written using expand() and nesting() as covered in the earlier section.

tibble(x = 1:2, y = c("a", "b")) %>%   expand(nesting(x, y), z = 1:3)

You can also use expand_grid() to expand matrices.

expand_grid(x1 = matrix(1:4, nrow = 2), x2 = matrix(5:8, nrow = 2))

Output:

# A tibble: 4 × 2
x1[,1] [,2] x2[,1] [,2]
<int> <int> <int> <int>
1 1 3 5 7
2 1 3 6 8
3 2 4 5 7
4 2 4 6 8