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
ソース化された R コードは次のとおりです。
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 の範囲範囲に入れ、変数名を範囲の最初の行に入れます。