我不知道是否有人可以看看下面的代碼和最小的例子,並提出改進建議 - 特別是關於工作時代碼的效率具有非常大的數據集。重複距離矩陣計算的高效(記憶方式)功能和超大距離矩陣的分塊
該函數接受一個data.frame並將其拆分爲一個分組變量(factor),然後計算每個組中所有行的距離矩陣。
我不需要保留距離矩陣 - 只有一些統計數據,即均值,直方圖..,然後他們可以被丟棄。
我對存儲器分配等知之甚少,不知道怎麼做纔是最好的辦法,因爲我將每組處理10.000 - 100.000個案例。任何想法將不勝感激!
另外,如果遇到嚴重的內存問題,將大內存或其他大型數據處理軟件包包含到函數中會是最痛苦的方式嗎?
FactorDistances <- function(df) {
# df is the data frame where the first column is the grouping variable.
# find names and number of groups in df (in the example there are three:(2,3,4)
factor.names <- unique(df[1])
n.factors <-length(unique(df$factor))
# split df by factor into list - each subset dataframe is one list element
df.l<-list()
for (f in 1:n.factors) {df.l[[f]]<-df[which(df$factor==factor.names[f,]),]}
# use lapply to go through list and calculate distance matrix for each group
# this results in a new list where each element is a distance matrix
distances <- lapply (df.l, function(x) dist(x[,2:length(x)], method="minkowski", p=2))
# again use lapply to get the mean distance for each group
means <- lapply (distances, mean)
rm(distances)
gc()
return(means)
}
df <- data.frame(cbind(factor=rep(2:4,2:4), rnorm(9), rnorm(9)))
FactorDistances(df)
# The result are three average euclidean distances between all pairs in each group
# If a group has only one member, the value is NaN
編輯:我編輯了標題,以反映分塊問題我張貼作爲一個答案..
翻翻碼,我開始懷疑它可能沒有做你想要完成的事情。然而,在代碼中缺乏任何評論使我們無法理解你認爲每條線將構建什麼。 –
對不起,我現在添加了評論(並清除了一些混亂) - 希望現在更清楚! – maja