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

有任何想法吗?

4

1 回答 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期间被回收。-

于 2013-05-31T15:06:08.957 回答