【发布时间】:2014-08-27 08:39:19
【问题描述】:
参考来自 Wilmott 论坛的this 问题,我刚刚编写了以下函数:
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
与 RInterface.GetArrayToVBA() 的错误用法有关,涉及从 R 到 VBA 的数组的维度和索引。
是否有人能够使上面的代码工作?一个只有五个或十个元素的数组的工作示例priceArray 和clustersNumber 等于 2 或 3 就足够了。
【问题讨论】: