如何将向量的每个元素的每个组合“合并”到单个列表中

时间:2018-12-07 14:31:33

标签: r list combn

我没有找到如何进行此特定转换的方法。有没有人有一个聪明的方法来实现这一目标?对不起,如果我错过了一个明显的答案。谢谢

# 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 )
)

1 个答案:

答案 0 :(得分:2)

遍历值的序列,获得向量的combn,其中m被指定为序列值,split由'col'组成,将嵌套列表展平为{{ 1}}个list中包含vectordo.call(c

unname

或者就像评论中提到的@IceCreamToucan

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