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

喜夏-厌秋 提交于 2019-12-01 03:55:30

问题


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     

回答1:


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]


来源:https://stackoverflow.com/questions/10516006/zoo-xts-cant-do-math-on-1-cell-subsets-r-hangs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!