假设我有一个包含唯一元素的 R 向量,例如 x <- c(1,2,3,4,5)
.
是否有一个函数可以给我这个向量的所有可能分区的列表x
?我猜每个分区都是一个向量列表,其中 x
中的每个元素属于向量之一。我希望将所有可能的分区分成任意数量的任意大小的集合。
(我认为此类分区的数量类似于 2^n * n!
,其中 n
是唯一元素的数量。我可能不会在具有超过 4 个唯一元素的向量上使用此函数。)
最佳答案
这是一个解决方案,可以为您提供完整的分区列表,每个分区都表示为一个向量列表。由于列表列表在打印到屏幕上时非常难看,因此我还向您展示了如何获得更 pretty-print 对象。
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()
在同一个包中,以更紧凑的方式来表示同一组分区。
关于r - 如何获得 R 中向量的所有可能分区的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10661105/