How can I get a list of all possible partitions of a vector in R?

后端 未结 2 677
清歌不尽
清歌不尽 2021-01-05 07:42

Suppose I have an R vector of unique elements such as x <- c(1,2,3,4,5).

Is there a function to give me a list of all possible partitions of this vec

相关标签:
2条回答
  • 2021-01-05 08:43

    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)
    

    See also setparts() in the same package for a more compact way to represent the same set of partitions.

    0 讨论(0)
  • 2021-01-05 08:46

    Does this give you what you are looking for,

    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))
    }
    
    0 讨论(0)
提交回复
热议问题