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

标签 r vector combinatorics

假设我有一个包含唯一元素的 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/

相关文章:

r - 如何提取每个日期时间戳的频率

r - 默认名称连接

c++ - STL 容器的内存消耗

c++ - 我应该如何格式化我的 .dat 文件以便制作 3D vector 图?

algorithm - 大小为 k 的所有子集,最大化子集之间的差异

r - RStudio没有选择我告诉它在读取文件时使用的编码

R - 带有周-年 : week is lost when converting to Date format 的字符串

r - Predict.glm 不预测缺失值作为响应

algorithm - 创建没有一个相交元素的组合

python - 可以并行生成排列吗?