Suppose I have a matrix A with N columns, and I take 2 (or any subset) of columns from this matrix to construct a new matrix B, for instance:
B = cbind(A[,1], A[,3])
Is there a simple argument I can add so that the header name for the two columns is transferred? Using names(B) = names(A) won’t work because the matrices are not the same dimension.
An example would help greatly since I suspect you may be using a dataframe which you are incorrectly calling a matrix. I say that because the names<- function used with a matrix would destroy the matrix structure. The proper function to modify column names is
colnames<-. Furthermore if you were extracting the columns from a matrix using the “[” function there is almost no way the the column names would not come across with the values:Responding to your comment, it would be better to do this:
Then your column names would be properly carried over. (Note added: I was surprised that your cbind operation did not bring the col.names over and wondered why that was so. This version of using “[” with cbind does retain the col.names:
The “[” function will coerce single columns or rows to an atomic vector and apparently also looses its dimnames attribute.
drop=FALSEprevents that loss.