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
有什么想法吗?
答案 0 :(得分:3)
下次,请提供 minimal 可重现的示例。例如:
> 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
属性,并且在使用matrix和zoo类对象进行子集化时不会丢弃它。您可以通过在子集调用中设置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]
会返回“vector xts”(即无量纲的xts对象),并且在x
调用期间向量会在-
内循环使用。