gpt4 book ai didi

r - 从 xts 对象的子集中减去 xts 对象

转载 作者:行者123 更新时间:2023-12-02 00:08:34 33 4
gpt4 key购买 nike

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

有什么想法吗?

最佳答案

下次,请提供一个最小可重现的例子。例如:

> 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 期间被回收- 调用。

关于r - 从 xts 对象的子集中减去 xts 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860040/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com