R Cluster export error “object not found”

2019-06-27 00:01发布

问题:

Can someone please help me understand why my program produces this error?

As can be seen here "pay.freq" clearly is part of the environment, so why can it not find it? Syntax is the same as for "ts" which it can find without problems

Big circle partly cvovers the word function, small circle partly covers the word plot.

cf.pro <- function(t=0,Tb=T,r=Y, k=1, PRFlag="P", freq="w",plot=0){ #Beregner exposure for alle tidspunkter med udgangspunkt 
  ts <- seq(0,30,1/52)
  pay.freq <- if(toupper(freq)=="W"){1}else #bestemmer hvor ofte der sker betalinger
    if(toupper(freq)=="Q"){13}else
      if(toupper(freq)=="H"){26}else
        if(toupper(freq)=="Y"){52}else print("Fejl i frequency input")

  library('parallel')
  cl <- makeCluster(7)
  clusterEvalQ(cl,source("C:/Users/Marcus/Documents/CBS/Speciale/Data/Global data.R"))
  clusterEvalQ(cl,source("C:/Users/Marcus/Documents/CBS/Speciale/Data/Swappriser.R"))
  clusterEvalQ(cl,source("C:/Users/Marcus/Documents/CBS/Speciale/Data/Interest simulation.R"))
  clusterEvalQ(cl,source("C:/Users/Marcus/Documents/CBS/Speciale/Data/Survival sim.R"))
  clusterEvalQ(cl,source("C:/Users/Marcus/Documents/CBS/Speciale/Data/Exposures.R"))
  clusterExport(cl,"ts")
  clusterExport(cl,"pay.freq")

 cf.pro <- parSapplyLB(cl,1:n, function(j){ #Beregner exposure serie n gange
    if (k==1) k=Swap(t=0,Ta=0,Tb=Tb,r=r[,j])
    sapply(ts,function(i){Exposure.cf(t=i,Tb=Tb,r=r[,j], k=k, PRFlag=PRFlag, pay.freq=pay.freq)}) #beregner exposure for alle tidspunkter
  })
  stopCluster(cl)

  if (plot==1) {
    tss <- seq(t, Tb, dt)
    matplot(tss, cf.pro[,1:n], type="l", lty=1, main="Exposure Profiles", ylab="Exposure") 
    lines(tss,rowMeans(cf.pro), lty=1, lwd=3)
  } 
  return(cf.pro)
}

CF.pro.w=cf.pro(t=0,Tb=T,r=r, PRFlag="P", freq="w", plot=1)

回答1:

If you take a look at the clusterExport documentation the call is the following

clusterExport(cl, varlist, envir = .GlobalEnv)

As you can see, the default environment to look for the variable you are trying to export is .GlobalEnv.

You are doing the export within the function, and the scope of pay.freq is not GlobalEnv but the local environment of the function. Yet you haven't specified the environment of the function to clusterExport, so clusterExport looks to GlobalEnv and doesn't find pay.freq.

I'm willing to bet this is your problem, and that pay.freq shows up in your environment now because you probably went line by line through your code to test. I'd clear your environment and try to run the code again by specifying the function environment to clusterExport.

Let me know how that goes, and we can maybe work through it if the problem is a bit more nuanced. This was just my first thought on looking at the question.