Getting all splits of a numerical sequence in R

I am trying to get all possible splitting sequences [1:n]in R. For example:

getSplits(0,3)

Should return all possible splitting sequences 123, in other words (in the list of vectors):

[1] 1
[2] 1 2
[3] 1 2 3
[4] 1 3
[5] 2
[6] 2 3
[7] 3

Now I created a function that recursively transitioned to these vectors, but could not combine them into one, as indicated above. My function:

getSplits <- function(currentDigit, lastDigit, split) {
  splits=list();
  for (nextDigit in currentDigit: lastDigit)
  {
    currentSplit <- c(split, c(nextDigit));
    print(currentSplit);
    if(nextDigit < lastDigit) {
      possibleSplits = c(list(currentSplit), getSplits(nextDigit+1, lastDigit, currentSplit));
    }else{
      possibleSplits = currentSplit;
    }
    splits <- c(splits, list(possibleSplits));
  }
  return(splits);
} 

If printing each currentSplit leads to all the vectors I need, but somehow the final list of returnt (splits) inserts them into deeper levels of the lists, returning:

[1] 1

[[1]][[2]]
[[1]][[2]][[1]]
[1] 1 2

[[1]][[2]][[2]]
[1] 1 2 3


[[1]][[3]]
[1] 1 3


[[2]]
[[2]][[1]]
[1] 2

[[2]][[2]]
[1] 2 3


[[3]]
[1] 3

To call the corresponding function getSplits(1, 3, c()).

If someone can help me get this to work as I described above, it would be very grateful!

+4
3

combn:

k <- 3
s <- unlist(lapply(1:k, combn, x = k, toString))
s
## [1] "1"       "2"       "3"       "1, 2"    "1, 3"    "2, 3"    "1, 2, 3"

, :

read.table(text = s, header = FALSE, sep = ",", fill = TRUE, col.names = 1:k)

:

  X1 X2 X3
1  1 NA NA
2  2 NA NA
3  3 NA NA
4  1  2 NA
5  1  3 NA
6  2  3 NA
7  1  2  3

:

lapply(s, function(x) scan(textConnection(x), quiet = TRUE, sep = ","))

:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 1 2

[[5]]
[1] 1 3

[[6]]
[1] 2 3

[[7]]
[1] 1 2 3

: , , , .

+6

:

f <- function(nums) sapply(1:length(nums), function(x) t(combn(nums, m = x)))
f(1:3)

[[1]]
     [,1]
[1,]    1
[2,]    2
[3,]    3

[[2]]
     [,1] [,2]
[1,]    1    2
[2,]    1    3
[3,]    2    3

[[3]]
     [,1] [,2] [,3]
[1,]    1    2    3
+3

OP is looking for a Power set c(1,2,3) . There are several packages that quickly you get this in one line. Using the package rje, we have:

library(rje)
powerSet(c(1,2,3))
[[1]]
numeric(0)

[[2]]
[1] 1

[[3]]
[1] 2

[[4]]
[1] 1 2

[[5]]
[1] 3

[[6]]
[1] 1 3

[[7]]
[1] 2 3

[[8]]
[1] 1 2 3

... and iterpc:

library(iterpc)
getall(iterpc(c(2,1,1,1), 3, labels = 0:3))
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    0    0    2
[3,]    0    0    3
[4,]    0    1    2
[5,]    0    1    3
[6,]    0    2    3
[7,]    1    2    3

More generally

n <- 3
getall(iterpc(c(n-1,rep(1, n)), n, labels = 0:n)) ## same as above
+3
source

Source: https://habr.com/ru/post/1690711/


All Articles