9

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

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

(我认为此类分区的数量类似于2^n * n!,其中n是唯一元素的数量。我可能不会在具有超过 4 个唯一元素的向量上使用此函数。)

4

2 回答 2

11

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

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)

另请参阅setparts()同一包中的一种更紧凑的方式来表示同一组分区。

于 2012-05-19T16:45:18.647 回答
0

这是否为您提供了您正在寻找的东西,

install.packages("gregmisc", dependencies = TRUE)
library(gregmisc)

x <- c(1,2,3,4,5)
for(i in 1:length(x)) {
print(combinations(5,i,x,repeats=TRUE))
}
于 2012-05-19T04:45:32.173 回答