【问题标题】:Generate a list of all permutations of matrices under conditions in R在R中的条件下生成矩阵的所有排列列表
【发布时间】:2021-06-04 19:08:18
【问题描述】:

我需要根据 R 中的这些条件生成一个 3x3 矩阵的所有排列的列表:

-第一行中唯一可能的值是 c(0,1,2)。

-第二行中唯一可能的值是 c(0,1)。

-最后一行唯一可能的值是0。

这里有几个例子:

0 0 1
0 0 0
0 0 0

1 0 2
0 1 0
0 0 0

2 2 1
1 1 0
0 0 0

所以我必须生成满足这些条件的所有现有矩阵。如果我没记错的话,我认为有 216 种排列。

【问题讨论】:

    标签: r list matrix combinations permutation


    【解决方案1】:
    library(plyr)
    library(magrittr)
    
    res <- 
      expand.grid(
        0:2, 0:2, 0:2,
        0:1, 0:1, 0:1,
        0, 0, 0
      ) %>% 
      as.matrix() %>% 
      alply(1, matrix, nrow = 3, byrow = TRUE)
    
    # remove redundant plyr attributes
    res <- res[1:length(res)]
    
    res
    #> $`1`
    #>      [,1] [,2] [,3]
    #> [1,]    0    0    0
    #> [2,]    0    0    0
    #> [3,]    0    0    0
    #> 
    #> $`2`
    #>      [,1] [,2] [,3]
    #> [1,]    1    0    0
    #> [2,]    0    0    0
    #> [3,]    0    0    0
    #> 
    #> $`3`
    #>      [,1] [,2] [,3]
    #> [1,]    2    0    0
    #> [2,]    0    0    0
    #> [3,]    0    0    0
    
    ...
    
    

    expand.grid 创建一个包含 9 个数字的所有组合的 data.frame,其中前三个数字可以是 0 到 2,后三个数字是 0 或 1,最后三个总是 0。所以基本上这是我们需要编写的矩阵在行中。确实有216个。现在我们只需要将行转换为 3x3 矩阵。 我能找到的最佳方法是将数据帧转换为矩阵,然后使用plyr::alply

    【讨论】:

      【解决方案2】:

      我不知道如何以函数式编程方式做到这一点,但这里是 for 循环方法。

      library(gtools)
      
      x <- permutations(3,3, c(0,1,2),repeats.allowed = TRUE)
      y <- permutations(2,3,c(0,1), repeats.allowed = TRUE)
      
      z = list()
      length = 1
      for(i in 1:nrow(x)){
        for(j in 1:nrow(y)){
        z[[length]]  <- (matrix(c(x[i,],y[j,],0,0,0), nrow = 3, byrow = TRUE))
         length = length + 1
        }
      }
      
      > length(z)
      [1] 216
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-21
        • 2020-12-19
        • 1970-01-01
        • 1970-01-01
        • 2013-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多