2013-05-31 1 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

다음은 좀 더 적용 할만한 것입니다 :'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 

문제는 그 객체가 기본적으로 dim 속성이하고 매트릭스와 동물원 클래스 객체처럼 서브 세트 때이 삭제되지 XTS입니다. 하위 설정 호출에서 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 함께 재활용되기 때문에이 작동합니다.