我寫了一個簡短的'for'循環來查找數據框中的每一行與所有其他行之間的最小歐幾里得距離(並記錄排最近)。理論上這避免了與嘗試計算非常大的矩陣的距離測量值相關的誤差。然而,雖然沒有太多的東西被保存在內存中,但對於大型矩陣非常緩慢(我的約150K行的使用案例仍在運行)。如何計算大數據幀的歐幾里得距離(僅保存彙總)
我想知道是否有人可以建議或指引我在正確的方向上矢量化我的功能,使用應用程序或類似的方面。對於看似簡單的問題表示歉意,但我仍在努力以矢量化的方式進行思考。
在此先感謝(和耐心等待)。
require(proxy)
df<-data.frame(matrix(runif(10*10),nrow=10,ncol=10), row.names=paste("site",seq(1:10)))
min.dist<-function(df) {
#df for results
all.min.dist<-data.frame()
#set up for loop
for(k in 1:nrow(df)) {
#calcuate dissimilarity between each row and all other rows
df.dist<-dist(df[k,],df[-k,])
# find minimum distance
min.dist<-min(df.dist)
# get rowname for minimum distance (id of nearest point)
closest.row<-row.names(df)[-k][which.min(df.dist)]
#combine outputs
all.min.dist<-rbind(all.min.dist,data.frame(orig_row=row.names(df)[k],
dist=min.dist, closest_row=closest.row))
}
#return results
return(all.min.dist)
}
#example
min.dist(df)
我沒有資格對矢量化進行評論,但是通過查找距離平方的最小值可以獲得一些好處,然後僅在返回時取平方根。 – 2013-05-10 02:26:00
你有檢查http://stackoverflow.com/questions/3029639/calculating-all-distances-between-one-point-and-a-group-of-points-efficiently-in?rq=1? – 2013-05-10 02:29:00
循環內的all.min.dist < - rbind(all.min.dist,...)非常糟糕,因爲它在每次迭代中創建一個更大的對象。閱讀*預先分配*。 – flodel 2013-05-10 02:33:28