Toolbox Toolbox - 1 month ago 10
R Question

xts cannot search a date without the timestamp, when using POSIXct

I have created below setup. The final result is an xts where the index
is formatted with

as.POSIXct
, including both date and time.

My question is how come cannot search in the index for a date,
excluding the time stamp in the search? Is there another way of being able to jump between searches for exclusive date without having to type the time?

Here is my code:

# create a set of test data to be used
d <- as.POSIXct(c("2014/10/06 06:30:00", "2015/02/02 12:27:00",
"2015/02/05 21:27:00", "2016/06/12 14:21:00"))
o = c(98.00, 97.67, 98.00, 98.10) # for "open" data
h = c(99.71, 98.97, 99.71, 99.41) # for "high" data
l = c(96.81, 96.86, 96.81, 97.70) # for "low" data
c = c(97.67, 98.67, 97.67, 98.83) # for "close" data
v = c(1000, 22000, 1000, 50000) # for "volume" data
a = c(1000, 22000, 1000, 50000) # for "adjusted" data

# create a dataframe
mydf1 <- data.frame("date" = d, "open" = o, "high" = h, "low" = l,
"close" = c, "volume" = v, "adjusted" = a)

# create an xts based on dataframe mydf1
myxts1 <- xts(mydf1[,-1], order.by = mydf1$date)


This command does not return any result.

myxts1[as.POSIXct("2014-10-06")]


...meanwhile all these commands works which indicates that the xts index
returns results.

first(myxts1, "year")
last(myxts1, "year")
myxts1[as.POSIXct("2014-10-06 06:30:00")]
window(myxts1, start = as.POSIXct("2015-02-02 12:27:00"),
end = as.POSIXct("2015-02-05 21:27:00"))

Answer

You want to use

myxts1["2014-10-06"]

If you supply a POSIXct object, xts tries to make an exact match, which it doesn't find in this case.