Question

This must be very simple, but I can't seem to find the solution. I need to compare the Close value for 2 xts objects

I have 2 xts objects:

>low2
low2           daco.Close
2013-07-24     6.63

>low3
low3           daco.Close
2013-07-24     2.63

But when I try something like this

if(low2$daco.Close < low3$daco.Close) {...}

I keep getting the error

Error in if (low2$daco.Close < low3$daco.Close) { : 
  argument is of length zero

Even though when I try print(low2) or print(low3) I get the correct values.

Any tip on how to solve this will be much appreciated. Thanks!

Edit: Following are the outputs of low2 and low3

> dput(low2)
structure(6.63, .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", src = "xxx", updated = structure(1374782893.98805, class = c("POSIXct", 
"POSIXt")), class = c("xts", "zoo"), index = structure(1374451200, tzone = "UTC", tclass = "Date"), .Dim = c(1L, 
1L), .Dimnames = list(NULL, "daco.Close"))
> dput(low3)
structure(2.63, .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", src = "xxx", updated = structure(1374782893.98805, class = c("POSIXct", 
"POSIXt")), class = c("xts", "zoo"), index = structure(1374624000, tzone = "UTC", tclass = "Date"), .Dim = c(1L, 
1L), .Dimnames = list(NULL, "daco.Close"))
Was it helpful?

Solution

xts objects are aligned by index before operations are done. Note that low2$daco.Close + low3$daco.Close probably doesn't return what you thought it would either.

This is what you are passing to your if statement:

> low2$daco.Close < low3$daco.Close     
     [,1]
> str(low2$daco.Close < low3$daco.Close)
An 'xts' object of zero-width

You can use coredata on one or both of the xts objects.

low2$daco.Close < coredata(low3$daco.Close)
#           daco.Close
#2013-07-22      FALSE

or you could coerce one or both of them to numeric first

as.numeric(low2$daco.Close) < as.numeric(low3$daco.Close)
#[1] FALSE

If they did in fact have the same index it should have just worked.

index(low3) <- index(low2)
low2$daco.Close < low3$daco.Close
#           daco.Close
#2013-07-22      FALSE
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top