Search code examples
rcombinationscategoriesfactors

Listing ALL combinations of Factors


Given the following data frame:

data_frame = data.frame(food = c("pizza", "tacos", "nachos"), drinks = c("water", "coffee", "pop"))

 data_frame
    food drinks
1  pizza  water
2  tacos coffee
3 nachos    pop

Is there a way to list ALL combinations of these factors?

For example:

food_combinations = c("none", pizza", "tacos", "nachos", "pizza & tacos", "pizza & nachos", "tacos & nachos", "pizza & tacos & nachos")

drink_combinations = c("none", coffee", "pop", "water", "coffee & pop", "coffee & water", "pop & water", "coffee & pop & water")

Thanks!


Solution

  • We can use combn to do - loop over the columns with lapply, then do a nested loop over the sequence of the elements, apply combn and paste

    lst1 <- lapply(data_frame, \(x) c("none", unlist(lapply(seq_len(length(x)),
            \(i) combn(x, i, FUN = paste, collapse = " & ")))))
    

    -output

    > lst1
    $food
    [1] "none"                   "pizza"                  "tacos"                  "nachos"                 "pizza & tacos"          "pizza & nachos"        
    [7] "tacos & nachos"         "pizza & tacos & nachos"
    
    $drinks
    [1] "none"                 "water"                "coffee"               "pop"                  "water & coffee"       "water & pop"          "coffee & pop"        
    [8] "water & coffee & pop"