2

Say one is trying to paste two matrices together, both of which have been given column labels using a list() with colnames(). Using cbind() in R works as expected for the data, but the column labels seem to get lost after the cbind() operation (the column labels become V1, V2, etc...). This would be part of a function and each matrix would be an input to the function so one or both of the matrices being appended would usually contain a different number of columns (but always the same number of rows).

Is there a way to retain the column names when binding the two matrices using cbind(), or is there an alternative way to append one matrix to the other that will retain the column labels?

Thanks in advance!

Dennis
  • 51
  • 1
  • 4
  • This seems to work: `m1<-matrix(1:8, nrow=2, dimnames=list(NULL, letters[1:4])); m2<-matrix(1:6, nrow=2, dimnames=list(NULL, letters[5:7])); cbind(m1,m2)`. Can you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) of a case where it doesn't work? – MrFlick Apr 16 '15 at 22:18
  • Thanks, this is going in the right direction. Using code: > colnm1 <- t(c(1,0,0)) > colnm2 <- t(c(1,1,0)) > colnm3 <- t(c(1,1,1)) > vectorlist <- list(colnm1,colnm2,colnm3) That works, but for the second input to dimnames, I am trying to pull the values "colnm1", "colnm2", "colnm3". – Dennis Apr 17 '15 at 05:05
  • Using the following code, I get the contents, not the names: > m1 <- matrix(colnm1,nrow=3,dimnames=list(NULL,vectorlist[1])) > m2 <- matrix(colnm2,nrow=3,dimnames=list(NULL,vectorlist[2])) > m3 <- matrix(colnm3,nrow=3,dimnames=list(NULL,vectorlist[3])) > finalmtx <- cbind(m1,m2,m3) > finalmtx c(1, 0, 0) c(1, 1, 0) c(1, 1, 1) [1,] 1 1 1 [2,] 0 1 1 [3,] 0 0 1 – Dennis Apr 17 '15 at 05:06
  • What's `vectorlist`? Probably should be `vectorlist[[1]]`. But you should edit your question with a *reproducible example* as already requested (rather than posting in comments) – MrFlick Apr 17 '15 at 05:17

1 Answers1

0

It's not totally clear what you mean by " given column labels using a list() with colnames()"

Using the following code retains the column names previously assigned to the matrices:

B = matrix(  c(2, 4, 3, 1, 5, 7),    nrow=3,  ncol=2) 
C = matrix(  c(12, 34, 33, 11, 35, 27),    nrow=3,  ncol=2) 

colnames(B)<-list("red","blue")
colnames(C)<-list("green","black")

D<-cbind(B,C)
colnames(D)
phocav
  • 144
  • 1
  • 6
  • If you change green to red in colnames (C), then cbind generates a new name for concatenated column. so you do not have two column names red and red. and cbind generates red and red.1. this is what exactly Dennis asks in this question. he wants to have exactly the same names without any changes by cbind – Heaven Apr 21 '21 at 09:59