在 R 中的条件下生成矩阵的所有排列的列表
Generate a list of all permutations of matrices under conditions in R
我需要根据 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种排列,如果我没记错的话。
我不知道如何以函数式编程的方式做到这一点,但这是 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
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
创建一个 data.frame 9 个数字的所有组合,其中前三个数字可以是 0 到 2,后三个数字可以是 0 或 1,最后三个数字始终是 0。所以基本上这是我们需要的矩阵写成行。确实有 216 个。现在我们只需要将行变成 3x3 矩阵。
我能找到的最好方法是将数据帧转换为矩阵,然后使用 plyr::alply
.
我需要根据 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种排列,如果我没记错的话。
我不知道如何以函数式编程的方式做到这一点,但这是 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
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
创建一个 data.frame 9 个数字的所有组合,其中前三个数字可以是 0 到 2,后三个数字可以是 0 或 1,最后三个数字始终是 0。所以基本上这是我们需要的矩阵写成行。确实有 216 个。现在我们只需要将行变成 3x3 矩阵。
我能找到的最好方法是将数据帧转换为矩阵,然后使用 plyr::alply
.