0

I have a vector wih 3 elements tempo <- c("VAR1", "VAR2", "VAR3")

Is there a functionwhich can give me all combinations of thoses elements without repetition? I want a result like : tempo2 <- c("VAR1", "VAR2", "VAR3", "VAR1 + VAR2", "VAR1 + VAR3", "VAR2 + VAR3")

I first tried using expand.grid(tempo,tempo) but it gives me "VAR1 VAR2" but also "VAR2 VAR1".

do you have an idea?

Thanks a lot!!

DD chen
  • 169
  • 11

3 Answers3

1

You were on a good track

@library(tidyverse) 
tempo <- c("VAR1", "VAR2", "VAR3")

You won't need the factors; they'll get in the way.

expand.grid(tempo,tempo, stringsAsFactors = FALSE)  %>% 
    # Generate all the combinations, but sort them before you paste them into a string.
  mutate(Combo = map2_chr(Var1, Var2,
         ~ paste(sort(unique(c(.x, .y))), collapse = " + "))) %>% 
    # You've cut down the combinations to only those in sort-order
  pull(Combo) %>% 
    # Get rid of the duplicates
  unique

# [1] "VAR1"        "VAR1 + VAR2" "VAR1 + VAR3" "VAR2"        "VAR2 + VAR3" "VAR3"       

Q.E.D.

David T
  • 1,993
  • 10
  • 18
1

We can use combn

c(tempo, combn(tempo, 2, FUN = paste, collapse=" + "))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

If you need a sets based solution, you can try this. You will have to adjust the loop index to stop at 2 and get rid of NULL set if you don't need it.

library("sets")
all_sub = NULL
for (i in 1:length(x)) {
  all_sub = set_union(all_sub, set_combn(x,i))
}
Shan R
  • 521
  • 4
  • 8