首页 文章

获取R中数字序列的所有拆分

提问于
浏览
4

我正试图在R.中获得序列 [1:n] 的所有可能分裂 .

getSplits(0,3)

应该返回序列123的所有可能的分裂,换句话说(在向量列表中):

[1] 1
[2] 1 2
[3] 1 2 3
[4] 1 3
[5] 2
[6] 2 3
[7] 3

现在我已经创建了一个函数,它可以递归地获取这些向量,但是无法将它们组合成一个如上所述 . 我的功能是:

getSplits <- function(currentDigit, lastDigit, split) {
  splits=list();
  for (nextDigit in currentDigit: lastDigit)
  {
    currentSplit <- c(split, c(nextDigit));
    print(currentSplit);
    if(nextDigit < lastDigit) {
      possibleSplits = c(list(currentSplit), getSplits(nextDigit+1, lastDigit, currentSplit));
    }else{
      possibleSplits = currentSplit;
    }
    splits <- c(splits, list(possibleSplits));
  }
  return(splits);
}

打印每个currentSplit导致我需要的所有正确向量,但不知何故最终返回列表(拆分)将它们嵌入到更深层次的列表中,返回:

[1] 1

[[1]][[2]]
[[1]][[2]][[1]]
[1] 1 2

[[1]][[2]][[2]]
[1] 1 2 3


[[1]][[3]]
[1] 1 3


[[2]]
[[2]][[1]]
[1] 2

[[2]][[2]]
[1] 2 3


[[3]]
[1] 3

对于相应的函数调用 getSplits(1, 3, c()) .

如果有人能按照我上面描述的方式帮助我完成这项工作,我们将不胜感激!

3 回答

  • 3

    字符向量输出

    试试 combn

    k <- 3
    s <- unlist(lapply(1:k, combn, x = k, toString))
    s
    ## [1] "1"       "2"       "3"       "1, 2"    "1, 3"    "2, 3"    "1, 2, 3"
    

    数据帧输出

    如果您希望输出采用数据框的形式:

    read.table(text = s, header = FALSE, sep = ",", fill = TRUE, col.names = 1:k)
    

    赠送:

    X1 X2 X3
    1  1 NA NA
    2  2 NA NA
    3  3 NA NA
    4  1  2 NA
    5  1  3 NA
    6  2  3 NA
    7  1  2  3
    

    列表输出

    或列表:

    lapply(s, function(x) scan(textConnection(x), quiet = TRUE, sep = ","))
    

    赠送:

    [[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
    

    Update: 已纳入评论中提到的改进以及一个进一步的简化,并添加了数据框和列表输出 .

  • 3

    这是另一种方法:

    f <- function(nums) sapply(1:length(nums), function(x) t(combn(nums, m = x)))
    f(1:3)
    

    这产生了

    [[1]]
         [,1]
    [1,]    1
    [2,]    2
    [3,]    3
    
    [[2]]
         [,1] [,2]
    [1,]    1    2
    [2,]    1    3
    [3,]    2    3
    
    [[3]]
         [,1] [,2] [,3]
    [1,]    1    2    3
    
  • 6

    OP正在寻找 c(1,2,3)c(1,2,3) . 有几个软件包可以在一行中快速获得 . 使用包 rje ,我们有:

    library(rje)
    powerSet(c(1,2,3))
    [[1]]
    numeric(0)
    
    [[2]]
    [1] 1
    
    [[3]]
    [1] 2
    
    [[4]]
    [1] 1 2
    
    [[5]]
    [1] 3
    
    [[6]]
    [1] 1 3
    
    [[7]]
    [1] 2 3
    
    [[8]]
    [1] 1 2 3
    

    ......和 iterpc

    library(iterpc)
    getall(iterpc(c(2,1,1,1), 3, labels = 0:3))
         [,1] [,2] [,3]
    [1,]    0    0    1
    [2,]    0    0    2
    [3,]    0    0    3
    [4,]    0    1    2
    [5,]    0    1    3
    [6,]    0    2    3
    [7,]    1    2    3
    

    更普遍,

    n <- 3
    getall(iterpc(c(n-1,rep(1, n)), n, labels = 0:n)) ## same as above
    

相关问题