[英]How to generate all possible m combinations in R, with m varying
我們如何在R中生成所有可能的組合(可變長度,以便結果列表的長度為1,2或3,如果有3個元素)來自可變長度的向量:
# say we have a vector of length 3:
vec = letters[1:3]
ret = list('a', 'b', 'c', 'ab', 'ac', 'bc', 'abc', 'a,b', 'a,c', 'a,bc', 'b,c', 'ac,b', 'ab,c', 'a,b,c')
謝謝!
這是一種方法,但對於較長的向量,它表現不佳。 這可能是一種更簡潔的方式,但在此期間這可能就足夠了。
get_combos <- function(x) {
x2 <- unlist(lapply(seq_along(x), function(m)
sapply(combn(x, m, simplify=FALSE), paste0, collapse='')))
x3 <- expand.grid(rep(list(x2), length(x)))
x4 <- sapply(apply(x3, 1, unique), function(x) paste0(sort(x), collapse=','))
unique(grep('.*([^,]).*\\1', x4, val=TRUE, invert=TRUE))
}
get_combos(letters[1:3])
## [1] "a" "a,b" "a,c" "a,bc" "a,b,c" "b" "b,c" "ac,b"
## [9] "c" "ab,c" "ab" "ac" "bc" "abc"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.