我的序列长度不一,例如类似的东西:
items <- 1:4
我想将其拆分为n
个数量集的每个可能组合。所以说n
是两个,我想回复:
Set A Set B
----- -----
1 2 3 4
1 2 3 4
1 2 3 4
1 3 2 4
等。集合内的安排无关紧要,即集合{1
,2
,3
}与{2
,1
,{{1 }}}。集不能为空。
我能想出的最佳结果(使用3
包中的permn
)是:
combinat
这是相当无用的,因为它返回相等的集合,即{n <- 2
r <- 1:length(items)
arrangements <- NULL
for (i in 1:(n-1)) {
A <- r[(1:i)]
B <- r[-(1:i)]
arrangements <- c(arrangements, apply(do.call(rbind, permn(1:length(items))), 1, function(z) list(z[A], z[B])))
}
,1
,2
}和{3
,2
,{{ 1}}}并且不够灵活,无法处理1
的不同值。任何人有任何想法我怎么能这样做?谢谢。
答案 0 :(得分:5)
有一套'套餐':
require(sets)
power_set(1:4)
sapply( set_power(1:4) , function(x) set_complement(x ,as.set(1:4)) )
list( Set_A = as.list(set_power(1:4)),
Set_B = sapply( set_power(1:4) , function(x) set_complement(x ,as.set(1:4)) ) )
它包括像({1,2,3,4},{})这样的配对,从设定理论的角度来看是正确的,但你可能想要将它们消除为“退化”。 (现在很明显,通过递归地处理Set_B结果,将其推广到更大的N.)
答案 1 :(得分:1)
这是另一种方式,可能对您有所帮助:
# Params
n <- 2
items <- 1:4
# Sample
l <- lapply(items, function(x) combn(items, x, simplify=F))
l <-unlist(l, recursive=F)
# devide into sets
tmp <- 1:length(l)
tmp <- split(tmp, sample(1:n, length(l), replace=T))
sets <- lapply(tmp, function(x) l[x])