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"}
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With