Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all consecutive subsets of a vector?

Tags:

r

subset

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"}

like image 347
vonjd Avatar asked Jan 13 '18 14:01

vonjd


1 Answers

A base R option would be embed

lapply(seq_along(v), function(i) embed(v, i)[, i:1, drop = FALSE])
#[[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"
like image 86
akrun Avatar answered Oct 03 '22 11:10

akrun