如何获得R中矢量的所有可能分区的列表?

Rya*_*son 5 r vector combinatorics

假设我有一个独特元素的R向量,如x <- c(1,2,3,4,5).

有没有函数给我一个这个向量的所有可能分区的列表x?我猜每个分区都是一个向量列表,其中每个元素都x属于一个向量.我想将所有可能的分区分成任意大小的任意数量的集合.

(我认为这样的分区的数量是这样的2^n * n!,其中n是唯一元素的数量.我可能不会在具有4个以上唯一元素的向量上使用此函数.)

Jos*_*ien 8

这是一个解决方案,它将为您提供一个完整的分区列表,每个分区都表示为一个向量列表.由于列表列表在打印到屏幕时非常难看,我还向您展示了如何获得更好的打印对象.

library(partitions)

x <- c(2,4,6)       # Substitute the vector for which you want partitions 
parts <- listParts(length(x))
out <- rapply(parts, function(ii) x[ii], how="replace")

# This step is for cosmetic purposes only. It allows you to take advantage of
# the `print.equivalence` print method when printing the object to a console 
for(i in seq_along(out)) class(out[[i]]) <- c("list", "equivalence")
out
[[1]]
[1] (2,4,6)

[[2]]
[1] (2,6)(4)

[[3]]
[1] (2,4)(6)

[[4]]
[1] (4,6)(2)

[[5]]
[1] (2)(4)(6)
Run Code Online (Sandbox Code Playgroud)

另请参见setparts()相同的程序包,以获得更紧凑的方式来表示同一组分区.