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

时间:2019-03-08 05:08:37

标签: r combinations permutation

我想对我的矩阵进行所有组合。
例如二进制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  

。 。

Com吗?:

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软件包,但找不到解决方案。

2 个答案:

答案 0 :(得分: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)))
}

答案 1 :(得分:0)

使用const posts = await Post .query() .select( 'Post.*', Post.relatedQuery('comments').count().as('numberOfComments') ); console.log(posts[4].numberOfComments); (我是作者),我们可以通过2个调用来完成此操作。也相当快:

RcppAlgos

以下是输出:

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
相关问题