How do I extract rownames from a matrix?

2020-08-20 03:53发布

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.

标签: r matrix rowname
1条回答
三岁会撩人
2楼-- · 2020-08-20 04:51

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)
查看更多
登录 后发表回答