Wilmott Forums からのこの質問を参照して、次の関数を作成しました。
Public Function KmeansPrice(ByVal priceArray As Range, _
ByVal clustersNumber As Integer) As Double
' Following rows are reproducible only if RExcel has been installed
' on your Excel!
Dim y() As Double
RInterface.StartRServer
RInterface.PutArrayFromVBA "x", priceArray
RInterface.PutArrayFromVBA "n", clustersNumber
RInterface.RRun "x = as.numeric(x)"
RInterface.RRun "cluster = kmeans(x, n)$cluster"
RInterface.RRun "bestBid = rep(NA, n)"
RInterface.RRun "for(i in 1:n)" & _
"{" & _
" assign(paste('group.', i, sep = ''), " & _
" x[cluster == i]);" & _
" bestBid[i] = max(get(paste('group.', i, sep = '')))" & _
"}"
RInterface.RRun "y = min(bestBid) + 0.01"
y = RInterface.GetArrayToVBA("y")
KmeansPrice = y(0, 0)
End Function
もちろん、R
以前にプロトタイプを作成したことがあり、適切に機能していたので、このエラーの原因は次のとおりだと思います。
Error -2147220501
in Module RExcel.RServer
Error in variable assignment
から VBA へRInterface.GetArrayToVBA()
の配列の次元とインデックス付けに関係する for の間違った使用法に関連しています。R
上記のコードを機能させることができる人はいますか? priceArray
2 または 3にclustersNumber
等しい5 個または 10 個の要素の配列を使用した実際の例で十分です。