2

I failed at searching for how to do this specific transformation. Does anyone have a smart way to achieve this? sorry if I missed an obvious answer somewhere. thanks

# start with a single vector
1:3

# achieve this desired structure, containing every combination
# from combn( x , 1 ) thru combn( x , length( x ) )
list(
    1 ,
    2 , 
    3 ,
    c( 1 , 2 ) ,
    c( 1 , 3 ) ,
    c( 2 , 3 ) ,
    c( 1 , 2 , 3 )
)
Anthony Damico
  • 5,779
  • 7
  • 46
  • 77

1 Answers1

2

Loop through the sequence of values, get the combn of the vector with m specified as the sequence values, split by 'col', flatten the nested list to a list of vectors with do.call(c and unname it

unname(do.call(c, lapply(1:3, function(x) {
      x1 <- combn(1:3, x)
      split(x1, col(x1))})))
#[[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

Or as @IceCreamToucan mentioned in the comments

do.call(c, lapply(1:3, function(x) combn(1:3, x, simplify = FALSE)))
akrun
  • 874,273
  • 37
  • 540
  • 662