在 R 中使用循环回归的 Difftime 错误

Difftime Error using Looping Regressions in R

使用下面的代码我得到了错误 Error in Ops.difftime((f - mean(f)), 2) : '^' not defined for "difftime" objects

此错误仅在包含位于循环末尾的 r_sq[[counter-lookback]] <- summary(temp_lm)$r.squared; 时发生。我在网上找不到任何类似的错误解决方案。谢谢您的帮助。

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

#Measure time used in processing
ptm <- proc.time()

#########
#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 data frame of both price series
AB_DF <- data.frame(A,B)

#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 of the spread, incrementing by 1, beginning at T = lookback+1

######## 
# Change below variable to alter length of data in regression
lookback <- 250
#######

#Initialize a counter, and lists to hold data from the spread regressions
counter <- lookback+1
res_store <- list()
spread_coef <- list()
r_sq <- list()
while (counter<length(SP)) {
    temp_lm <- lm(TS[(counter-lookback):counter]~SP[(counter-lookback):counter]);
    res_store[[counter-lookback]] <- residuals(temp_lm);
    spread_coef[[counter-lookback]] <- coefficients(temp_lm)[[2]];
    r_sq[[counter-lookback]] <- summary(temp_lm)$r.squared;
    counter <- counter+1;
  }

好的,我已经弄明白了。问题是 R 不喜欢为按时间索引的数据计算 R^2 值。通过使数据值随时间回归,difftime() 中会发生错误。我通过将索引从时间值更改为标准整数索引来解决这个问题,并且一切 运行 都很好。