[英]R function combination of vectors
我有一個帶有 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”。
你有想法嗎?
非常感謝!!
你在一個很好的軌道上
@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"
量子點
我們可以使用combn
c(tempo, combn(tempo, 2, FUN = paste, collapse=" + "))
如果您需要基於集合的解決方案,您可以試試這個。 如果不需要,您將不得不調整循環索引以停止在 2 並擺脫 NULL 設置。
library("sets")
all_sub = NULL
for (i in 1:length(x)) {
all_sub = set_union(all_sub, set_combn(x,i))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.