Run macro with Rexcel

谁都会走 提交于 2019-12-02 17:24:57

问题


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.


回答1:


Answer goes to @jlhoward.

You have a typo in your VBA-code. Instead of:

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

you should use

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

i.e. in your R code you are using pweights (plural) but in VBA code you use pweight (singular).



来源:https://stackoverflow.com/questions/22691280/run-macro-with-rexcel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!