R函数的向量组合

问题描述 投票:0回答:3

我的向量有3个元素tempo <- c("VAR1", "VAR2", "VAR3")

是否有一个函数可以给我这些元素的所有组合而无需重复?我想要这样的结果:tempo2 <- c("VAR1", "VAR2", "VAR3", "VAR1 + VAR2", "VAR1 + VAR3", "VAR2 + VAR3")

我首先尝试使用expand.grid(tempo,tempo),但它给了我“ VAR1 VAR2”,但也给了我“ VAR2 VAR1”。

你有想法吗?

非常感谢!

r
3个回答
0
投票

您进展顺利

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

您不需要这些因素;他们会妨碍您。

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。


0
投票

如果需要基于集合的解决方案,可以尝试一下。您将需要调整循环索引以将其停止在2处,如果不需要它,请摆脱掉NULL集。

library("sets")
all_sub = NULL
for (i in 1:length(x)) {
  all_sub = set_union(all_sub, set_combn(x,i))
}

0
投票

我们可以使用combn

c(tempo, combn(tempo, 2, FUN = paste, collapse=" + "))
© www.soinside.com 2019 - 2024. All rights reserved.