Referring to this question from Wilmott Forums, I've just written the following function:
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
Of course I've prototyped it in R
before and it worked properly, then I guess that the cause of this error:
Error -2147220501
in Module RExcel.RServer
Error in variable assignment
is related to the wrong usage of RInterface.GetArrayToVBA()
for what concerns dimensions and indexing of arrays from R
to VBA.
Is anyone able to make the code above work? A working example with an array of just five or ten elements as priceArray
and clustersNumber
equal to 2 or 3 would be sufficient.