0

我在 VBA 中使用 Rexcel 运行宏:

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,range)
将 R 变量 var 的值(需要是数据框)放入 Excel 范围范围,将变量名称放在范围的第一行。

4

1 回答 1

0

答案转到@jlhoward。

您的 VBA 代码中有错字。代替:

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

你应该使用

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

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

于 2019-07-31T16:11:56.053 回答