Search code examples
rdata-bindingmatrixcbind

Combine selected columns from many matrices


I am trying to accomplish the following task to get to matrix d:

d1<-matrix(as.factor(rep(sample(1:10,10,T),5)),ncol=5)
d2<-matrix(as.factor(rep(sample(1:10,10,T),5)),ncol=5)
d3<-matrix(as.factor(rep(sample(1:10,10,T),5)),ncol=5)

d<-cbind(
  cbind(d1[,2],d1[,5]),
  cbind(d2[,2],d2[,5]),
  cbind(d3[,2],d3[,5])
)

But for many matrices d1...dn, say.

More generally I would like to select the same column numbers from a series of matrices and append into a single matrix. The focus of this task is on combining, not creating the matrices. The factor-type column vectors should be preserved.

I thought about something along the lines of

d<-matrix(nrow=10)
dl<-list(d1,d2,d3)
for (i in 1:3){
  d<-cbind(d,dl[[i]][,2],dl[[i]][,5])
}

But maybe there is a better way.


Solution

  • You can create a list of your matrices and use do.call and lapply to get what you want:

    matList <- list(d1, d2, d3)
    do.call(cbind, lapply(matList, function(x) x[, c(2, 5)]))
    #       [,1] [,2] [,3] [,4] [,5] [,6]
    #  [1,] "3"  "3"  "3"  "3"  "10" "10"
    #  [2,] "4"  "4"  "2"  "2"  "3"  "3" 
    #  [3,] "6"  "6"  "7"  "7"  "7"  "7" 
    #  [4,] "10" "10" "4"  "4"  "2"  "2" 
    #  [5,] "3"  "3"  "8"  "8"  "3"  "3" 
    #  [6,] "9"  "9"  "5"  "5"  "4"  "4" 
    #  [7,] "10" "10" "8"  "8"  "1"  "1" 
    #  [8,] "7"  "7"  "10" "10" "4"  "4" 
    #  [9,] "7"  "7"  "4"  "4"  "9"  "9" 
    # [10,] "1"  "1"  "8"  "8"  "4"  "4" 
    

    By the way, the data type in your matrix is character, not factor. See the help page at ?matrix where you will find the following:

    The method for data frames will return a character matrix if there is only atomic columns and any non-(numeric/logical/complex) column, applying as.vector to factors and format to other non-character columns.