2016-11-20 61 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