【问题标题】:function that makes all combinations of permutations in r在 r 中进行所有排列组合的函数
【发布时间】:2023-03-12 14:21:01
【问题描述】:

我有数字向量

n_vector = c(0,1)

我有 k 个号码。我需要制作所有排列组合的数据框。对于 k=3,它应该是:

0 0 0
0 0 1
0 1 0
1 0 0
0 1 1
1 0 1
1 1 0
1 1 1

对于 k =4,结果应该是:

0 0 0 0
0 0 0 1
0 0 1 0
0 1 0 0
1 0 0 0
0 0 1 1
0 1 0 1
1 0 0 1
0 1 1 0
1 0 1 0
1 1 0 0
1 1 1 0
1 1 0 1
1 0 1 1
0 1 1 1
1 1 1 1

是否有任何标准的函数库可以制作这样的数据框?

【问题讨论】:

    标签: r dataframe matrix permutation combinatorics


    【解决方案1】:

    你可以结合replicateexpand.grid来做这样的功能

    fun <- function(x) {
       do.call("expand.grid", replicate(x, 0:1, simplify = FALSE))
    }
    fun(3)
    fun(4)
    

    或者使用一些按位逻辑的另一种选择:

    fun <- function(x) {
      outer(0:(2^x-1), 2^(0:(x-1)), function(a, b) as.numeric(bitwAnd(a, b)>0))
    }
    

    【讨论】:

      【解决方案2】:

      这就是 RcppAlgos::permuteGeneral 的设计目的。速度极快,因为用 C++ 实现。

      library(RcppAlgos)
      permuteGeneral(c(0, 1), 3, repetition=TRUE)
      #      [,1] [,2] [,3]
      # [1,]    0    0    0
      # [2,]    0    0    1
      # [3,]    0    1    0
      # [4,]    0    1    1
      # [5,]    1    0    0
      # [6,]    1    0    1
      # [7,]    1    1    0
      # [8,]    1    1    1
      permuteGeneral(c(0, 1), 4, repetition=TRUE)
      #       [,1] [,2] [,3] [,4]
      #  [1,]    0    0    0    0
      #  [2,]    0    0    0    1
      #  [3,]    0    0    1    0
      #  [4,]    0    0    1    1
      #  [5,]    0    1    0    0
      #  [6,]    0    1    0    1
      #  [7,]    0    1    1    0
      #  [8,]    0    1    1    1
      #  [9,]    1    0    0    0
      # [10,]    1    0    0    1
      # [11,]    1    0    1    0
      # [12,]    1    0    1    1
      # [13,]    1    1    0    0
      # [14,]    1    1    0    1
      # [15,]    1    1    1    0
      # [16,]    1    1    1    1
      

      【讨论】:

        【解决方案3】:
        #install if necessary
        install.packages('gtools')
        #load library
        library(gtools)
        #urn with 3 balls
        x <- c('red', 'blue', 'black')
        #pick 2 balls from the urn with replacement
        #get all permutations
        permutations(n=3,r=2,v=x,repeats.allowed=T)
        #      [,1]    [,2]   
        # [1,] "black" "black"
        # [2,] "black" "blue" 
        # [3,] "black" "red"  
        # [4,] "blue"  "black"
        # [5,] "blue"  "blue" 
        # [6,] "blue"  "red"  
        # [7,] "red"   "black"
        # [8,] "red"   "blue" 
        # [9,] "red"   "red"
        #number of permutations
        nrow(permutations(n=3,r=2,v=x,repeats.allowed=T))
        #[1] 9
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多