参考 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
与从数组到 VBARInterface.GetArrayToVBA()
的维度和索引的错误使用有关。R
有没有人能让上面的代码工作?priceArray
一个只有五个或十个元素的数组的工作示例clustersNumber
就足够了。