Florent Florent - 1 year ago 47
R Question

How to format Index() without TZ information in R?

I would like to test if the date of the last row of an xts object is equal to the current date. My problem is that

returns the timezone information the
function doesn't.

> last(index(obj))
[1] "2016-09-16 UTC"

> Sys.Date()
[1] "2016-09-16"

The workaround I have is to
but it not elegant. Is there a better solution ?

# Test if we already have data
if (last(index(obj)) == paste0(Sys.Date(), " ", Sys.timezone())) {



* EDIT *

More info :

> str(obj)
An ‘xts’ object on 2013-06-01/2016-09-16 containing:
Data: num [1:1204, 1:6] NA NA NA NA NA NA NA NA NA NA ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:6] "Open" "High" "Low" "Close" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ: UTC
xts Attributes:
List of 1
$ dateFormat: chr "Date"

Thank you,

Answer Source

The timezone is printed because index(obj) is a POSIXct class object. If you want to compare the output of index(obj) with the output from Sys.Date(), you need to ensure that the output of index is a Date class object. There are a couple ways to accomplish this:

1) Directly convert the output of index to Date:

as.Date(last(index(obj))) == Sys.Date()

2) Convert the entire index of obj to Date (note that the index class is currently POSIXct):

indexClass(obj) <- "Date"
last(index(obj)) == Sys.Date()