问题
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.
回答1:
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)
来源:https://stackoverflow.com/questions/14301498/how-do-i-extract-rownames-from-a-matrix