首页 文章

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

提问于
浏览
5

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

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

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

2 回答

  • 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)
    

    另请参见同一包中的setparts(),以更紧凑的方式表示同一组分区。

  • 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))
    }
    

相关问题