如何获得R中向量的所有可能分区的列表? [英] How can I get a list of all possible partitions of a vector in R?
问题描述
假设我有一个唯一元素的R向量,例如 x<-c(1,2,3,4,5)
。
Suppose I have an R vector of unique elements such as x <- c(1,2,3,4,5)
.
有没有给我这个向量 x
的所有可能分区的列表的函数?我猜每个分区都是一个向量列表,其中 x
中的每个元素都属于其中一个向量。我希望将所有可能的分区划分为任意数量的任意大小的集合。
Is there a function to give me a list of all possible partitions of this vector x
? I guess each partition would be a list of vectors, where each element in x
belongs to one of the vectors. I want all possible partitions into any number of sets of any size.
(我认为此类分区的数量类似于 2 ^ n * n!
,其中 n
是唯一元素的数量。我可能不会在具有4个以上唯一元素的向量上使用此函数。)
(I think the number of such partitions is something like 2^n * n!
, where n
is the number of unique elements. I will probably not be using this function on vectors with more than 4 unique elements.)
推荐答案
这里是一个解决方案,它将为您提供完整的分区列表,每个分区都表示为向量列表。由于列表列表在打印到屏幕上时非常难看,因此,我还向您展示了如何获得打印效果更好的对象。
Here's a solution that will get you a complete list of partitions, each one of which is represented as a list of vectors. Since a list of lists is pretty ugly when printed to the screen, I've also shown you how to get a more nicely printed object.
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()
在同一包中,以更紧凑的方式表示同一组分区。
See also setparts()
in the same package for a more compact way to represent the same set of partitions.
这篇关于如何获得R中向量的所有可能分区的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!