expand_grid: Create a tibble from all combinations of inputs

Description Usage Arguments Value Examples

View source: R/expand.R

Description

expand_grid() is heavily motivated by expand.grid(). Compared to expand.grid(), it:

Usage

1
expand_grid(..., .name_repair = "check_unique")

Arguments

...

Name-value pairs. The name will become the column name in the output.

.name_repair

Treatment of problematic column names:

  • "minimal": No name repair or checks, beyond basic existence,

  • "unique": Make sure names are unique and not empty,

  • "check_unique": (default value), no name repair, but check they are unique,

  • "universal": Make the names unique and syntactic

  • a function: apply custom name repair (e.g., .name_repair = make.names for names in the style of base R).

  • A purrr-style anonymous function, see rlang::as_function()

This argument is passed on as repair to vctrs::vec_as_names(). See there for more details on these terms and the strategies used to enforce them.

Value

A tibble with one column for each input in .... The output will have one row for each combination of the inputs, i.e. the size be equal to the product of the sizes of the inputs. This implies that if any input has length 0, the output will have zero rows.

Examples

1
2
3
4
5
6
7
expand_grid(x = 1:3, y = 1:2)
expand_grid(l1 = letters, l2 = LETTERS)

# Can also expand data frames
expand_grid(df = data.frame(x = 1:2, y = c(2, 1)), z = 1:3)
# And matrices
expand_grid(x1 = matrix(1:4, nrow = 2), x2 = matrix(5:8, nrow = 2))

Example output

# A tibble: 6 x 2
      x     y
  <int> <int>
1     1     1
2     1     2
3     2     1
4     2     2
5     3     1
6     3     2
# A tibble: 676 x 2
   l1    l2   
   <chr> <chr>
 1 a     A    
 2 a     B    
 3 a     C    
 4 a     D    
 5 a     E    
 6 a     F    
 7 a     G    
 8 a     H    
 9 a     I    
10 a     J    
# … with 666 more rows
# A tibble: 6 x 2
   df$x    $y     z
  <int> <dbl> <int>
1     1     2     1
2     1     2     2
3     1     2     3
4     2     1     1
5     2     1     2
6     2     1     3
# A tibble: 4 x 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

tidyr documentation built on Sept. 27, 2021, 5:07 p.m.