Home > other >  Appending multiple matrices and vector into a single matrix in R
Appending multiple matrices and vector into a single matrix in R

Time:10-26

I have a function that can create a matrix given the k and n value. Where each row combinations add upto k and n is the number of columns. Example: if k=3 and n=20 then

library(partitions)
posloc<- function(k, n){
  df = t(as.matrix(blockparts(rep(k,n),k, include.fewer = FALSE)))
  indx <- !duplicated(t(apply(df, 1, sort)))
  (df[indx, ])
}

posloc(4,5)

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

I need to append all the matrices until k:0 into a single matrix. For example I want my final matrix to look like this

     [,1] [,2] [,3] [,4] [,5]
[1,]    4    0    0    0    0
[2,]    3    1    0    0    0
[3,]    2    2    0    0    0
[4,]    2    1    1    0    0
[5,]    1    1    1    1    0
[6,]    3    0    0    0    0
[7,]    2    1    0    0    0
[8,]    1    1    1    0    0
[9,]    2    0    0    0    0
[10,]   1    1    0    0    0
[11,]   1    0    0    0    0
[12,]   0    0    0    0    0

I have tried he following but I always end up with a matrix containing only the last row

for(i in k:0){
  assign(paste0("pc_", i), posloc(i,n))
}

for(i in k:0){
  temp <- rbind(get(eval(paste0("pc_", i, sep=""))))
}

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

Can someone please help me figure out what I am doing wrong to get the matrix I want? Thank you.

CodePudding user response:

Using sapply.

do.call(rbind, sapply(4:0, function(k) posloc(k, 5)))
#       [,1] [,2] [,3] [,4] [,5]
#  [1,]    4    0    0    0    0
#  [2,]    3    1    0    0    0
#  [3,]    2    2    0    0    0
#  [4,]    2    1    1    0    0
#  [5,]    1    1    1    1    0
#  [6,]    3    0    0    0    0
#  [7,]    2    1    0    0    0
#  [8,]    1    1    1    0    0
#  [9,]    2    0    0    0    0
# [10,]    1    1    0    0    0
# [11,]    1    0    0    0    0
# [12,]    0    0    0    0    0

If you want to stick with for loop, you should first initialize an empty matrix.

m <- matrix(nrow=0, ncol=5)
for (i in 4:0) {
 m <- rbind(m, posloc(i, 5))
}
#       [,1] [,2] [,3] [,4] [,5]
#  [1,]    4    0    0    0    0
#  [2,]    3    1    0    0    0
#  [3,]    2    2    0    0    0
#  [4,]    2    1    1    0    0
#  [5,]    1    1    1    1    0
#  [6,]    3    0    0    0    0
#  [7,]    2    1    0    0    0
#  [8,]    1    1    1    0    0
#  [9,]    2    0    0    0    0
# [10,]    1    1    0    0    0
# [11,]    1    0    0    0    0
# [12,]    0    0    0    0    0
  • Related