Run macro with Rexcel

2019-03-03 10:48发布

Are there some Rexcel experts in here?:)

I am running a macro with Rexcel in VBA:

Sub create_efficient_frontier()

 RInterface.StartRServer

 Sheets("Analys").Range("A52:K82").ClearContents

 RInterface.PutDataframe "datat", Range("ChosenData!X181:AD352")
 RInterface.PutArray "startdate", Range("Analys!K2")
 RInterface.PutArray "enddate", Range("Analys!K3")

RInterface.RunRFile "C:/Users/Documents/EffFront.R"

RInterface.GetDataframe "hmz$pweight", Range("Analys!A51:E76")

End Sub

The sourced R code is:

myfront=function(datat,startdate,enddate){
  library(fPortfolio)
  datat=datat[startdate:enddate,]
  datanew=datat[sapply(datat[1,], function(x) !any(is.na(x)))] 

  datatss=as.timeSeries(datanew,datanew[,1])

  Spec = portfolioSpec()
  Constraints = "Long-Only"
  globminhfrxmed=minvariancePortfolio(
    data = datatss,
    spec = Spec,
    constraints = Constraints)

  setNFrontierPoints(Spec) <- 25
  globminfrontier <- portfolioFrontier(datatss,Spec, Constraints)

  thelisttoret<-vector(mode="list")

  pweights<-globminfrontier@portfolio@portfolio$weights
  pweights<-data.frame(pweights)
  names(pweights)=colnames(globminfrontier@portfolio@portfolio$covRiskBudgets)
  thelisttoret[["pweights"]]<-pweights

  tret<-globminfrontier@portfolio@portfolio$targetReturn[,1,drop=FALSE]
  thelisttoret[["tret"]]<-tret

  trisk<-globminfrontier@portfolio@portfolio$targetRisk[,2,drop=FALSE]
  thelisttoret[["trisk"]]<-trisk

  return(thelisttoret)
}

hmz=myfront(datat,startdate,enddate)

That seems to work but the first row (where the names should be) is #RError. But the code works correctly in R.

It is strange because when I read online it says RInterface.GetDataframe(varname,range) Puts the value of R variable var (which needs to be a dataframe) into Excel range range, putting variable names in the first row of the range.

Any idea what I am doing wrong?

Best Regards!

0条回答
登录 后发表回答