2013-05-31 111 views
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對象中減去特定列的問題。從xts對象的子集中減去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 

任何想法?

+0

SIT使用XTS對象封裝時間序列,所以我不認爲這會是一個問題。如果你做str(ret),它是一個xts對象。 – user1234440

+0

SIT用XTS對象包裝時間序列。上面的例子只是下載數據並讓SIT將它包裹在一個XTS對象周圍。但我現在將它編輯爲「最小」版本。 – user1234440

+0

下面是一些更像'apply'-like:'sweep(x,1,x [,3])' – GSee

回答

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再循環。