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

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

Is there a function to give me a list of all possible sections of this vector x? I think each section will be a list of vectors, where each element of xbelongs to one of the vectors. I want all possible sections to be in any number of sets of any size.

(I think the number of such sections is similar to 2^n * n!, where nis the number of unique elements. Probably, I will not use this function for vectors with more than 4 unique elements.)

+3
source share
2 answers

, , . , , .

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() .

+6

, ,

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

All Articles