r语言 - 运行宏与excel



我正在运行一个宏与reexcel在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

源代码为:

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)

这似乎工作,但第一行(名称应该在哪里)是#RError。但是代码在r中可以正常工作。

这很奇怪,因为当我在线阅读时它显示

RInterface.GetDataframe (varname、范围)
将R变量var的值(需要是一个数据框)放入Excel范围范围,将变量名称放在范围的第一行。

答案归@jlhoward。

您的vba代码中有一个错别字。而不是:

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

你应该使用

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

。在您的R代码中,您使用pweights(复数),但在VBA代码中,您使用pweight(单数)。

最新更新