Dail
Dail

Reputation: 4606

How to read the index of a data.frame?

I have a data.frame like this:

> aaa
           AdjClose
2012-01-03   15.5
2012-01-04   18.8
2012-01-05   13.9

Doing dt$AdjClose I get get the "column" with the prices, but, how to get the dates ?

Thank you!

Upvotes: 0

Views: 113

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174778

rownames(aaa) will give them to you. Do note that they will be a character vector, not something R considers dates. For that you need to convert the characters to dates using as.Date(). This is illustrated below:

> aaa
           AdjClose
2012-01-03     15.5
2012-01-04     18.8
2012-01-05     13.9
> rownames(aaa)
[1] "2012-01-03" "2012-01-04" "2012-01-05"
> class(rownames(aaa))
[1] "character"
> as.Date(rownames(aaa))
[1] "2012-01-03" "2012-01-04" "2012-01-05"
> class(as.Date(rownames(aaa)))
[1] "Date"

I didn't need to specify a format for the as.Date() call as your characters are already in the default format.

Upvotes: 4

Related Questions