Home > Enterprise >  expand all columns using column names
expand all columns using column names

Time:03-27

I would like to get all possible combinations of all column values in a dataframe e.g.

library(tidyr)

# example data
fruits <- tibble(
  type   = c("apple", "orange", "banana"),
  year   = c(2010, 2011, 2012),
  size  =  c("XS", "S",  "M"),
  weights = rnorm(3, 2)
)

# this works
expand(fruits, type, year, size, weights)

But in my real dataframe I want to expand over many columns and i) don't want to enter all column names manually and ii) won't always know the column names in advance. I was hoping this would work, but it doesn't.

expand(fruits, names(fruits))

Is there a way to use something like names(), to automatically expand all columns?

CodePudding user response:

do.call(expand, c(list(fruits), lapply(names(fruits), as.symbol)))
# # A tibble: 81 x 4
#    type   year size  weights
#    <chr> <dbl> <chr>   <dbl>
#  1 apple  2010 M       0.994
#  2 apple  2010 M       2.25 
#  3 apple  2010 M       2.34 
#  4 apple  2010 S       0.994
#  5 apple  2010 S       2.25 
#  6 apple  2010 S       2.34 
#  7 apple  2010 XS      0.994
#  8 apple  2010 XS      2.25 
#  9 apple  2010 XS      2.34 
# 10 apple  2011 M       0.994
# # ... with 71 more rows
  • Related