Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zoo/xts - can't do math on 1-cell subsets? R hangs

Tags:

r

zoo

xts

I'm using latest version of R/xts/zoo on Windows: R 2.15, xts 0.8-6, zoo 1.7-7

I'm seeing the following bizarre behavior, which was not the case with prior versions:

library(xts)
data(sample_matrix)
sample.xts <- as.xts(sample_matrix)

sample.xts[1, 2] - sample.xts[2,2]     # results in numeric(0)?!?!?!
(sample.xts[ 1, 2] - sample.xts[2,2])/sample.xts[3,1]  # if I run this twice R locks up

Here I have subset an XTS object to a single cell. Subtraction no longer works. Also, division causes R to completely lock up.

Does anyone else see this? Is this a known bug or am I missing something? I can reproduce this on two machines.

Session Info (a few packages deleted as confidential):

R version 2.15.0 (2012-03-30)
Platform: x86_64-pc-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] parallel  stats     graphics  utils     datasets  grDevices methods   base     
like image 772
SFun28 Avatar asked Nov 04 '22 00:11

SFun28


1 Answers

You never could subtract xts/zoo objects with non-overlapping indices. Arithmetic operations always merge before performing the operation. You need to use coredata in order for the subtraction you've written to provide the result you expect.

coredata(sample.xts[1,2]) - coredata(sample.xts[2,2])

I can replicate the second issue but I'm not sure this should be a high priority to fix, because it doesn't fit the zoo/xts idiom and would result in a completely empty xts object. Everything is fine if (some of) the indices align.

(sample.xts[1,2] - sample.xts[1,3]) / sample.xts[1,4]
(sample.xts[2,2] - sample.xts[1:2,3]) / sample.xts[2:3,4]
like image 121
Joshua Ulrich Avatar answered Nov 07 '22 23:11

Joshua Ulrich