2021年1月26日星期二

R value of i and j in a loop

I am learning to run a loop (2 rounds of loop) for a DCC GARCH model. However, the loop is out of my control because:

Problem 1: Round 1, I want R to run for i from 1 to n-1 (n is total numbers of countries): however it keeps run from i==0 --> I put i in (2:length(msci)-1); so it is ok for now, but I just don't understand why there is the case.

Round 2, I want R to run for j from i+1 to n. Somehow, R run j until n+ 1 --> I bypass it by setting

j in (i+1:length(msci)-1

It is ok for i=1 (it runs for j from 2 to 49). When i=2, it runs from 3 to 50

So it issues the error: "[1] "Now is loop j 50" Error in [.data.frame(msci, j) : undefined columns selected"

Any help (how to stop j reach the value of 50) is greatly appreciated. thanks

My code is:

library(R.oo)  library(rmgarch)  library(tidyverse)  setwd("C:/data/Garch output")  #define the function####  my_model <- function(country1, country2) {    uspec <- ugarchspec(variance.model = list(model="eGARCH",garchOrder = c(1,1)),mean.model = list(armaOrder = c(2,2)))    mspec=multispec(replicate(2,uspec))    multf=multifit(mspec,data=data.frame(country1,country2),solver = "nlminb",fit.control = list(stationarity = 1, fixed.se = 0, scale = 1, rec.init = "all"))        #define the DCC model    spec1=dccspec(uspec=mspec,dccOrder=c(1,1), model = "DCC",distribution="mvnorm")    #estimate DCC     fit1=dccfit(spec1,data=data.frame(country1,country2),fit.control = list(eval.e=TRUE),fit=multf)    return(fit1)      }    for (i in 2: length(msci)-1) {        print(paste("LOOP i IS NOW", i))        if (j >= i+1:length(msci)-1) {      if (i != j) {        print(paste("Now is loop j", j))        print(paste("this is the loop of correlation between", names(msci[i]), "and", names(msci[j])))        #create name for the output        temp_name <- paste0("fit_",names(msci[i]), "_", names(msci[j]))        file_name <- temp_name        #estimate model        temp_name <- tryCatch({my_model(msci[i], msci[j])},                              error = function(e) {cat("There is a error in", names(msci[i]), "and", names(msci[j]), "\n")}        )        saveRDS(temp_name, file = paste0(file_name,".RDS"))        print(paste("Finish loop of correlation between", names(msci[i]), "and", names(msci[j])))      }            }}  

my data is in the below google link.

https://docs.google.com/spreadsheets/d/1ygaoOvby4mTpFIfHTkcyjq-Uwby671yQWI-xfU3Li7Y/edit#gid=0

https://stackoverflow.com/questions/65912093/r-value-of-i-and-j-in-a-loop January 27, 2021 at 10:27AM

没有评论:

发表评论