user1815498
user1815498

Reputation: 1287

transferring header names for matrix columns in R

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.

Upvotes: 2

Views: 5518

Answers (2)

IRTFM
IRTFM

Reputation: 263481

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:

> mat <- matrix(1:9, 3)
> colnames(mat) <- letters[1:3]
> mat[ , 2:3]
     b c
[1,] 4 7
[2,] 5 8
[3,] 6 9

Responding to your comment, it would be better to do this:

B <- A[ , c(1,3) ]

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:

> B=cbind( A[,1,drop=FALSE], A[,3,drop=FALSE])
> B
     a c
[1,] 1 7
[2,] 2 8
[3,] 3 9

The "[" function will coerce single columns or rows to an atomic vector and apparently also looses its dimnames attribute. drop=FALSE prevents that loss.

Upvotes: 3

agstudy
agstudy

Reputation: 121618

You can use subset with 'select' ?subset

 B <- subset(A,select = c(col1,col2))  

e.g

 A <- mtcars
 B <- subset(A,select = c(mpg,cyl))

                      mpg cyl
Mazda RX4         21.0   6
Mazda RX4 Wag     21.0   6
Datsun 710        22.8   4
Hornet 4 Drive    21.4   6
Hornet Sportabout 18.7   8
Valiant           18.1   6

if you do by index :

      B=cbind(A[,1],A[,3])
      colnames(B) <- colnames(A)[c(1,3)]

Upvotes: 1

Related Questions