Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keep column names when applying as.vector to a matrix slice

Let us say I have a matrix,

A = matrix(c(1,23,4,5,6,3,2,2,1,2), nrow = 2, ncol = 5)

with rownames and column names given by,

rownames(A) = c('row1', 'row2')
colnames(A) = c('es', 'one', 'column', 'no', '5')

If I do:

> my.slice = A[1,,drop=FALSE]
    es    one column     no      5 
     1      4      6      2      1 

I still see the column names. But if I do:

> my.slice = as.numeric(A[1,,drop=FALSE])
[1] 1 4 6 2 1

I lost the column names, and both are actually of numeric class.

Is there a way to do as.vector and keep the column names? Or more generally, to slice the matrix into a numeric class vector with names(my.slice) = colnames(A)?

It all started when I set up the default to be drop=FALSE. Then I need to do as.vector when i slice matrices but sadly now I loose the names of the elements in my.slice.

like image 209
Dnaiel Avatar asked Oct 23 '25 14:10

Dnaiel


1 Answers

Using setNames:

(my.slice = setNames(A[1,], colnames(A)))
es    one column     no      5 
 1      4      6      2      1 

class(my.slice)
[1] "numeric"
like image 114
tflutre Avatar answered Oct 25 '25 03:10

tflutre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!