R 变量初始化问题:"number of items to replace is not a multiple of replacement length"

R Variable Initialization Trouble: "number of items to replace is not a multiple of replacement length"

我正在尝试对两个金融时间序列的切片进行相互回归,并将每个回归的结果存储在单个对象中。当 运行 这段代码时,我得到 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])

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

的使用
...
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]])

lm_store 被初始化为空向量 (class NULL)。当您将 lm 的结果传递给 lm_store 时,您将传回 'lm' 的 class,这是一个包含 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]])

请注意 R 中列表的双括号“[[]]”。这应该可以解决您的问题。