-Edit: adopted the response by @akrun as it is more concise and doesn't rely on any packages
Here is an alternative way, in the form of a function. Parameter m
allows you to choose the maximum elements in each phrase.
df <- data.frame(
food = c("pizza", "tacos", "nachos"),
drinks = c("water", "coffee", "pop")
)
comb1 <- function(vector, m = length(vector)) {
if (m >= length(vector)) {
data <- unlist(lapply(seq_len(length(df$food)),
\(i) combn(df$food, i, paste, collapse = ' & ')))
}
else {
data <- unlist(lapply(seq_len(m),
\(i) combn(df$food, i, paste, collapse = ' & ')))
}
return(data)
}
Which renders
> comb1(df$food)
[1] "none" "nachos" "pizza"
[4] "tacos" "nachos & pizza" "nachos & tacos"
[7] "pizza & tacos" "nachos & pizza & tacos"
> comb1(df$food,2)
[1] "none" "nachos" "pizza" "tacos" "nachos & pizza"
[6] "nachos & tacos" "pizza & tacos"
For a list over the dataframe then just a lapply
> lapply(df, comb1)
$food
[1] "none" "nachos" "pizza"
[4] "tacos" "nachos & pizza" "nachos & tacos"
[7] "pizza & tacos" "nachos & pizza & tacos"
$drinks
[1] "none" "coffee" "pop"
[4] "water" "coffee & pop" "coffee & water"
[7] "pop & water" "coffee & pop & water"
> lapply(df, \(x) comb1(x,2))
$food
[1] "none" "nachos" "pizza" "tacos" "nachos & pizza"
[6] "nachos & tacos" "pizza & tacos"
$drinks
[1] "none" "coffee" "pop" "water" "coffee & pop"
[6] "coffee & water" "pop & water"