1

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

上記のコードを機能させることができる人はいますか? priceArray2 または 3にclustersNumber等しい5 個または 10 個の要素の配列を使用した実際の例で十分です。

4

1 に答える 1

1

クラスタリング機能に詳しくありませんが、これは壊れずに結果を返します。

私は R エディターで関数を作成してからコードをソースすることを好むので、これを R で行い、R 関数をソースしました。

kmeansPrice <- function(priceArray,clustersNumber)
{
  `[` <- function(...) base::`[`(...,drop=FALSE) #in case we have a 1 dimensional table
  x<-priceArray
  n<- clustersNumber
  x<-matrix(as.numeric(x),nrow=dim(x)[1],ncol=dim(x)[2])
  cluster = kmeans(x, n)$cluster
  bestBid = rep(NA, n)
  for(i in 1:n)
  {
    assign(paste('group.', i, sep = ''),
    x[cluster == i])
    bestBid[i] = max(get(paste('group.', i, sep = '')))
  }
  return(min(bestBid) + 0.01)
}

次に、次のことができます

Public Function KmeansPrice(ByVal priceArray As Range, _
                            ByVal clustersNumber As Integer) As Double

rinterface.PutArrayFromVBA "priceArray", priceArray.Value 'I think this ".Value" was your problem'
rinterface.PutArrayFromVBA "clustersNumber", clustersNumber
rinterface.RRun "theResult <- kmeansPrice(priceArray,clustersNumber)"
y = rinterface.GetRExpressionValueToVBA("theResult") 'preferred to GetArrayToVBA for single-value results'
KmeansPrice = y
End Function

サンプルデータで実行します: に評価される 2x4 テーブル

     [,1] [,2]
[1,]    5    9
[2,]    6   10
[3,]    7   11
[4,]    8   12

3つの「クラスター」

Sub runkmeans()
theResult = KmeansPrice(Range("BH2:BI5"), 3)
MsgBox (theResult)
End Sub

6.01が得られます

于 2014-09-03T18:59:21.093 に答える