2016-11-20 65 views
1

我之前问过类似这个问题。但是这个更棘手一点。我有无限正方程x1+x2+x3 = 8的正整数解(先前是非​​负解)矩阵(说A)。另外,我还有一个矩阵(比如B)与列使用不定方程的正整数解生成矩阵

0 1 0 1 
0 0 1 1 

我要生成使用A行和B列矩阵。

例如,令(2,2,4)是矩阵A的一个解决方案(一行)。在这种情况下,我不能使用rep。所以我试图从矩阵B生成所有三列矩阵,然后尝试应用rep,但无法弄清楚。我使用以下几行来生成所有三个列矩阵的列表。

cols <- combn(ncol(B), 3, simplify=F, FUN=as.numeric) 
M3 <- lapply(cols, function(x) cbind(B[,x])) 

有关示例,cols[[1]] [1] 1 2 3

然后,我的新矩阵的列将是这个新的矩阵的

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

列是B.即列的倍数,第一列2次,第二列2次和第三列4次。我想用这个程序矩阵A的所有行。我该怎么做?

回答

0

?rep(x, times)说;

如果次是相同的长度为x(复制后由每个 )的向量,其结果是由x的[1]重复次数[1]次中,x [2] 重复次数[2]次数等。

基本思路是;

B <- matrix(c(0, 1, 0, 1, 0, 0, 1, 1), byrow = T, nrow = 2) 
cols <- combn(ncol(B), 3, simplify=F, FUN=as.numeric) 

a1 <- c(2, 2, 4)  
cols[[1]] # [1] 1 2 3 
rep(cols[[1]], a1) # [1] 1 1 2 2 3 3 3 3 

B[, rep(cols[[1]], a1)] 
#  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] 
# [1,] 0 0 1 1 0 0 0 0 
# [2,] 0 0 0 0 1 1 1 1 
testA <- rbind(c(2,2,4), c(2,1,5), c(2,3,3)) 

## apply(..., lapply(...)) approach (output is list in list) 
apply(testA, 1, function(x) lapply(cols, function(y) B[, rep(y, x)])) 

## other approach using combination of indices 
ind <- expand.grid(ind_cols = 1:length(cols), ind_A = 1:nrow(testA)) 
col_ind <- apply(ind, 1, function(x) rep(cols[[x[1]]], testA[x[2],])) 

lapply(1:ncol(col_ind), function(x) B[, col_ind[,x]]) # output is list 

library(dplyr) 
apply(col_ind, 2, function(x) t(B[, x])) %>% matrix(ncol = 8, byrow=T) # output is matrix