For xts objects, the binary math and logical operators always align the two objects by their indexes before performing the operation. Therefore, you need to use lag
to appropriately align the index values if you want to use those operators on observations at different timestamps.
require(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
x$diff50 <- lag(x$Close, 50) - x$Close
Note that lag.xts
breaks the convention of lag.ts
and lag.zoo
(where a positive k
references data in the future) to use the more standard convention of a positive k
to reference historical (not future) data.
If you just want to subtract a scalar value that occurs at a single timestamp of an xts object, you can use coredata
to remove the index attribute.
nr <- nrow(symbol)
change <- coredata(Cl(symbol)[nr-50]) - Cl(symbol)[nr]