Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract rownames from a matrix?

Tags:

r

matrix

rowname

I have a matrix with rownames that are dates. I want to extract these row names into a variable, and then use rownames() to apply these dates to another matrix I have. Let's say the matrix is called 'data.matrix'.

Whenever I run:

data.matrix[,0]

I get a printout of all the dates. So I do this:

v <- data.matrix[,0]

When I return v I get a nice list of all the dates. But when I use:

rownames(other.matrix) <- v

And then I return:

head(other.matrix)

I don't get any new column names.

Also, when I try:

head(v)

I get NULL

But when I do:

v

I get a nice printout of all my dates.

So what gives? At first I thought that matrices and dates were incompatible but it seems as if they are.

Right now I'm using merge() in this way to add dates:

z <- merge(v, other.matrix)

But it feels like there's a better way to do this.

like image 276
user1613119 Avatar asked Jan 13 '13 07:01

user1613119


1 Answers

The command

data.matrix[,0]

does return a matrix object without columns. Hence, you see its row names only.

To extract the rownames from an object, use the rownames function:

v <- rownames(data.matrix)
like image 78
Sven Hohenstein Avatar answered Sep 27 '22 22:09

Sven Hohenstein