3
votes

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!

1
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 of a case where it doesn't work?MrFlick
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
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 1Dennis
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

1 Answers

1
votes

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)