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!!
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"
QED
We can use combn
c(tempo, combn(tempo, 2, FUN = paste, collapse=" + "))
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))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.