R可变初始化故障:"要替换的项目数不是替换长度的倍数"

时间:2015-01-11 20:01:06

标签: r loops variables statistics regression

我试图将两个金融时间序列的切片相互对照,并将每个回归的结果存储在一个对象中。运行此代码时,我得到50+相同的错误

50: In lm_store[counter - lookback] <- lm(SP[(counter - lookback):counter] ~  ... :
number of items to replace is not a multiple of replacement length" 

也许我正在初始化lm_store错误,但我无法找到解决方案,尽管反复变化。最后,我打印出lm_store[5]只是为了验证回归的结果。谢谢您的帮助。

#Import necessary packages
require(quantmod)
require(ggplot2)

#Write in the ticker symbols of the pair
tickers <- c("GS","JPM")

#Pull data down for symbols
A <- getSymbols(tickers[1],auto.assign=FALSE)
B <- getSymbols(tickers[2],auto.assign=FALSE)

#Strip data such as high and low prices
A <- A[,4]
B <- B[,4]

#Create a time series of the spread & rename header
S <- A-B
colnames(S) <- "Spread.Close"

#Separate the index of times from the spread data for regression
TS <- index(S)
SP <- coredata(S)

#Perform regressions of past 'lookback' days, incrementing by 1, beginning at T = lookback+1
#Store regression data in vector
lookback <- 250
counter <- lookback+1
lm_store = NULL
while (counter<length(SP)) {
    lm_store[counter-lookback] <- lm(SP[(counter-lookback):counter]~TS[(counter-lookback):counter]);
    counter <- counter+1;
  }

print(lm_store[5])

2 个答案:

答案 0 :(得分:0)

答案很简单。您使用错误的结构来存储结果。您需要使用list。请注意使用[[ vs [

...
lm_store <- list()
while (counter<length(SP)) {
    lm_store[[counter-lookback]] <- lm(SP[(counter-lookback):counter]~TS[(counter-lookback):counter]);
    counter <- counter+1;
  }

print(lm_store[[5]])

答案 1 :(得分:0)

lm_store初始化为空向量(类NULL)。当您将lm的结果传递给lm_store时,您将传回一类“lm”&#39;这是12个元素的列表。您需要做的是:

lm_store = list()
while (counter<length(SP)) {
    lm_store[[counter-lookback]] <- lm(SP[(counter-lookback):counter]~TS[(counter  lookback):counter]);
    counter <- counter+1;
  }

print(lm_store[[5]])

请注意双括号&#39; [[]]&#39;对于R中的列表。这应该可以解决您的问题。