2016-08-11 17 views
1

データ行列と中心の集合のユークリッド距離を計算したいと思います。重心からの距離の計算

私はこの関数を使用した:

Euclid <- function(df, centers) { 
    distanceMatrix <- matrix(NA, nrow=dim(df)[1], ncol=dim(centers)[1]) 
    for(i in 1:nrow(centers)) { 
    distanceMatrix[,i] <- sqrt(rowSums(t(t(df)-centers[i,])^2)) 
    } 
    distanceMatrix 
} 
df

列として行および寸法などの点を有するデータ行列です。それは840ポイントと11次元を持っています。

head(df) 

    v1  v2 v3  v4  v5  v6  v7  v8  v9  v10 v11 
1 -0.81 0.24 -0.36 -0.68 -0.51 -0.26 -0.82 0.53 0.19 0.17 0.92 
2 1.23 0.24 0.11 0.65 0.67 0.56 0.43 -0.19 -0.31 0.55 0.45 
3 -0.81 -0.59 -0.36 -0.35 0.28 0.15 0.02 -0.19 0.68 0.17 -0.02 

centersは、12行11次元の中心のマトリックスです。

head(centers) 

    v1  v2 v3  v4  v5  v6  v7  v8  v9  v10 v11 
1 0.29 0.09 0.19 0.02 -0.07 0.13 -0.01 0.09 0.02 0.15 0.09 
2 0.04 0.03 0.10 0.01 0.01 0.01 0.03 0.01 0.31 0.04 0.45 
3 0.07 0.02 -0.02 -0.02 0.48 0.36 -0.66 -0.09 0.21 -0.03 -0.78 

はしかし、Euclid関数を適用すると、次のエラーような結果になっています

distsToCenters <- Euclid(df, centers) 
    Error in distanceMatrix[, i] <- sqrt(rowSums(t(t(df) - centers[i, : 
    number of items to replace is not a multiple of replacement length 

私ははるかに小さい寸法の行列でこれを試してみたし、それがうまく働いています。しかし、私の現在のデータ・セットとセンター・マトリックスではうまく機能していないようです。

誰かが私に間違ったことを教えてもらえますか?事前に多くの感謝。

答えて

0

data.framesは、データ処理に適しています。しかし、matrixクラスとは異なる動作をします。あなたがここにいるのは、やや直感的ではない厄介なバグです。

Euclid <- function(df, centers) { 
    distanceMatrix <- matrix(NA, nrow = nrow(df), ncol = nrow(centers)) 
    df <- as.matrix(df) 
    centers <- as.matrix(centers) 
    for(i in 1:nrow(centers)) { 
    distanceMatrix[, i] <- sqrt(colSums((t(df) - centers[i, ])^2)) 
    } 
    return(distanceMatrix) 
} 

tmp1 <- data.frame(x=rnorm(5), y = rnorm(5)) 
tmp2 <- data.frame(x=rnorm(2), y = rnorm(2)) 

tmp1 
tmp2 
Euclid(tmp1, tmp2) 

sqrt(rowSums(t(t(as.matrix(df))-as.matrix(centers)[i,])^2)) 
# or at the start 
df <- as.matrix(df); centers <- as.matrix(centers) 

で作業例をsqrt(rowSums(t(t(df)-centers[i,])^2))を交換してみてください

関連する問題