从xts对象的子集中减去一个xts对象

3
con = gzcon(url('http://www.systematicportfolio.com/sit.gz', 'rb'))
source(con)
close(con)
load.packages("TTR,PerformanceAnalytics,quantmod,lattice")

#######################################################
#Get and Prep Data
#######################################################
data <- new.env()
tickers<-spl("VTI,IEF,TLT,DBC,VNQ,GLD")

getSymbols(tickers, src = 'yahoo', from = '1980-01-01', env = data)
for(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use.Adjusted=TRUE)

bt.prep(data, align='remove.na', dates='1990::2013')

我遇到了从xts对象中减去特定列的问题。

prices = data$prices
ret = prices / mlag(prices) - 1
ret - ret[,3]  #subtract column three from every other column don't seem to work

有没有快速解决方案?

我尝试过:

apply(ret,2,function(x) x - x[,3]) #doesn't seem to work

有什么想法吗?


SIT使用XTS对象来包装时间序列,所以我认为这不会是一个问题。如果你执行str(ret),它就是一个xts对象。 - user1234440
SIT使用XTS对象包装时间序列。上面的示例只是下载数据,然后使用SIT将其包装在XTS对象周围。但我现在将对其进行编辑,以获得“最小”版本... - user1234440
这里有一个更类似于apply的东西:sweep(x, 1, x[, 3]) - GSee
1个回答

3
下次请提供一个最小化的可重现示例,例如:

> library(xts)
> data(sample_matrix)
> x <- as.xts(sample_matrix)
> x-x[,1]
Error in `-.default`(x, x[, 1]) : non-conformable arrays
> apply(x, 2, function(y) y-x[,1])
Error in array(ans, c(len.a%/%d2, d.ans), if (!all(vapply(dn.ans, is.null,  : 
  length of 'dimnames' [1] not equal to array extent

问题在于xts对象默认具有dim属性,并且在子集化时不像矩阵和动物园类对象那样被删除。您可以通过在子集调用中设置drop=TRUE来强制删除它。
> head(x-x[,1,drop=TRUE])
           Open       High         Low       Close
2007-01-02    0 0.07799532 -0.08936727  0.07799532
2007-01-03    0 0.19137980  0.00000000  0.16717014
2007-01-04    0 0.00000000 -0.15681864 -0.08859811
2007-01-05    0 0.00000000 -0.15243423 -0.03887316
2007-01-06    0 0.00000000 -0.13311797 -0.06320448
2007-01-07    0 0.08349916 -0.14025780 -0.14025780

这是因为x[,1,drop=TRUE]返回一个“向量xts”(即无维度的xts对象),并且在-调用期间,该向量沿着x被循环利用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接