Use elements of array as names for expand_grid in R

Viewed 75

Im trying to use expand grid in a function.

Suppose:

key <- c("a", "g", "t", "c")
asd <- c("A", "B", "D")

for(i in asd){
  df = expand_grid(i = key)
}

What returns is:

# A tibble: 4 x 1
  i    
  <chr>
1 a    
2 g    
3 t    
4 c  

What I want is:

# A tibble: 64 x 3
     A    B     C
   <chr> <chr> <chr>
 1 a     a     a    
 2 a     a     g    
 3 a     a     t    
 4 a     a     c    
 5 a     g     a    
 6 a     g     g    
 7 a     g     t    
 8 a     g     c    
 9 a     t     a    
10 a     t     g    
# ... with 54 more rows

Which is for each element of my array to be the name and for the key to be the value.

In my minimum reproducible code to obtain this I should write:

df = expand_grid("A" = key,
                 "B" = key,
                 "C" = key)

But for the sake of what I want to do, which is a function, I want for "A" "B" "C"...."n" to be created based on another function. For the values of the returned array to be used as the names in expand grid.

1 Answers

We can replicate the vector, set the names and invoke the expand_grid

library(tidyr)
library(purrr)
out <- setNames(rep(list(key), length(asd)), asd) %>%
     invoke(expand_grid, .)

If we need a for loop to do this, initialize a data.frame/tibble with the vector first and then update that dataset on each iteration

df <- tibble(!!asd[1] := key)
for(i in asd[-1]) df <- expand_grid(df, !! i := key)

The base R expand.grid can be directly applied on a list of vectors

expand.grid(setNames(rep(list(key), length(asd)), asd) )
Related