How to get all consecutive subsets of a vector?

If I want to get all subsets of a vector I can e.g. use the sets package:

library(sets)
v <- c("test1", "test2", "test3", "test4")
set_power(v)
## {{}, {"test1"}, {"test2"}, {"test3"}, {"test4"}, {"test1",
##  "test2"}, {"test1", "test3"}, {"test1", "test4"}, {"test2",
##  "test3"}, {"test2", "test4"}, {"test3", "test4"}, {"test1",
##  "test2", "test3"}, {"test1", "test2", "test4"}, {"test1",
##  "test3", "test4"}, {"test2", "test3", "test4"}, {"test1",
##  "test2", "test3", "test4"}}

My question
How do I get only all subsets, where all the elements are consecutive, so in the above case without {"test1", "test3"}, {"test1", "test4"}, {"test2", "test4"}, {"test1", "test2", "test4"}, {"test1", "test3", "test4"}

Answer

Try rollapply like this:

library(zoo)
v <- c("test1", "test2", "test3", "test4")

L <- lapply(seq_along(v), rollapply, data = v, c)
L[[1]] <- matrix(L[[1]])

giving length(v) components, one for each subset size:

[[1]]
     [,1]   
[1,] "test1"
[2,] "test2"
[3,] "test3"
[4,] "test4"

[[2]]
     [,1]    [,2]   
[1,] "test1" "test2"
[2,] "test2" "test3"
[3,] "test3" "test4"

[[3]]
     [,1]    [,2]    [,3]   
[1,] "test1" "test2" "test3"
[2,] "test2" "test3" "test4"

[[4]]
     [,1]    [,2]    [,3]    [,4]   
[1,] "test1" "test2" "test3" "test4"

or as a flat list with one component per subset:

flat <- do.call("c", lapply(L, function(x) split(x, 1:nrow(x))))

giving:

> str(flat)
List of 10
 $ 1: chr "test1"
 $ 2: chr "test2"
 $ 3: chr "test3"
 $ 4: chr "test4"
 $ 1: chr [1:2] "test1" "test2"
 $ 2: chr [1:2] "test2" "test3"
 $ 3: chr [1:2] "test3" "test4"
 $ 1: chr [1:3] "test1" "test2" "test3"
 $ 2: chr [1:3] "test2" "test3" "test4"
 $ 1: chr [1:4] "test1" "test2" "test3" "test4"

Attribution
Source : Link , Question Author : vonjd , Answer Author : G. Grothendieck

Leave a Comment