R:矩阵组合具有特定数量的值

问题描述 投票:1回答:2

我想制作我的Matrix的所有组合。 防爆。二进制5 X 5矩阵,其中我只有两行1(见下文)

用1:

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

2:

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

. . .

有了?

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

我尝试在Combination中使用R包,但找不到解决方案。

r combinations permutation
2个回答
0
投票

使用RcppAlgos(我是作者),我们可以通过2次调用完成此操作。它也很快:

library(tictoc)
library(RcppAlgos)

tic("RcppAlgos solution")

## First we generate the permutations of the multiset c(1, 1, 0, 0, 0)
binPerms <- permuteGeneral(1:0, 5, freqs = c(2, 3))

## Now we generate the permutations with repetition choose 5
## and select the rows from binPerms above
allMatrices <- permuteGeneral(1:nrow(binPerms), 5, 
                              repetition = TRUE, 
                              FUN = function(x) {
                                  binPerms[x, ]
                              })
toc()
RcppAlgos solution: 0.108 sec elapsed

这是输出:

allMatrices[1:3]
[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    0    0    0
[2,]    1    1    0    0    0
[3,]    1    1    0    0    0
[4,]    1    1    0    0    0
[5,]    1    1    0    0    0

[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    0    0    0
[2,]    1    1    0    0    0
[3,]    1    1    0    0    0
[4,]    1    1    0    0    0
[5,]    1    0    1    0    0

[[3]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    0    0    0
[2,]    1    1    0    0    0
[3,]    1    1    0    0    0
[4,]    1    1    0    0    0
[5,]    1    0    0    1    0


len <- length(allMatrices)
len
[1] 100000

allMatrices[(len - 2):len]
[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    1
[2,]    0    0    0    1    1
[3,]    0    0    0    1    1
[4,]    0    0    0    1    1
[5,]    0    0    1    1    0

[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    1
[2,]    0    0    0    1    1
[3,]    0    0    0    1    1
[4,]    0    0    0    1    1
[5,]    0    0    1    0    1

[[3]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    1
[2,]    0    0    0    1    1
[3,]    0    0    0    1    1
[4,]    0    0    0    1    1
[5,]    0    0    0    1    1    

0
投票

我在下面写的代码对我有用。 100,000个5x5矩阵的列表。每个行都有两个设置为1的位置。

n <- 5 # No of columns
k <- 2 # No. of ones
m <- 5  # No of rows in matrix

nck <- combn(1:n,k,simplify = F)
possible_rows <-lapply(nck,function(x){
  arr <- numeric(n)
  arr[x] <- 1
  matrix(arr,nrow=1)
})

mat_list <- possible_rows
for(i in 1:(m-1)){
  list_of_lists <- lapply(mat_list,function(x){
    lapply(possible_rows,function(y){
      rbind(x,y)
    })
  })
  mat_list <- Reduce(c,list_of_lists)
  print(c(i,length(mat_list)))
}
© www.soinside.com 2019 - 2024. All rights reserved.