本文介绍了使用R中的循环回归的Difftime错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With the below code I am getting the error Error in Ops.difftime((f - mean(f)), 2) : '^' not defined for "difftime" objects.

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

This error only occurs with the inclusion of r_sq[[counter-lookback]] <- summary(temp_lm)$r.squared; which is located towards the end of the loop. I cannot find any similar error solutions online. Thank you for your help.

#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()中发生错误.我通过将索引从时间值更改为标准整数索引来解决此问题,一切运行正常.

Ok all, I have figured it out. The issue is that R does not like to compute R^2 values for data indexed by time. By regressing the data values against time, an error in difftime() occurs. I solved this by changing the index from time values to a standard integer index, and everything ran fine.

这篇关于使用R中的循环回归的Difftime错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 20:59