Suppose I have two vectors:
letters[1:2]
#> [1] "a" "b"
1:2
#> [1] 1 2
that I would like use as input to expand_grid()
, which takes a comma-separated sequence of name-value pairs:
library(tidyverse)
expand_grid(let = letters[1:2], num = 1:2)
#> # A tibble: 4 × 2
#> let num
#> <chr> <int>
#> 1 a 1
#> 2 a 2
#> 3 b 1
#> 4 b 2
Created on 2025-06-04 with reprex v2.1.1
Or takes a comma-separated sequence of names of vectors:
let <- letters[1:2]
num <- 1:2
library(tidyverse)
expand_grid(let, num)
#> # A tibble: 4 × 2
#> let num
#> <chr> <int>
#> 1 a 1
#> 2 a 2
#> 3 b 1
#> 4 b 2
Created on 2025-06-04 with reprex v2.1.1
Now suppose I have a third vector:
lgl <- c(T, F)
How could I create an object that is interpreted by expand_grid()
as a sequence of two of the three vectors? For example, suppose I would like to create a similar table by randomly taking two of the three vectors and supplying them as input to expand_grid()
without knowing which two vectors were chosen.
[This question is not about expand_grid()
specifically, but about tidyverse functions that expect a sequence of name-value pairs or (data-masked) names of vectors. For example, here is the equivalent context for the expand()
function:
library(tidyverse)
tibble(let = letters[1:2], num = 1:2) |>
expand(let, num)
#> # A tibble: 4 × 2
#> let num
#> <chr> <int>
#> 1 a 1
#> 2 a 2
#> 3 b 1
#> 4 b 2
Created on 2025-06-04 with reprex v2.1.1
]