我不知道是否有人可以看看下面的代码和最小的例子,并提出改进建议 - 特别是关于工作时代码的效率具有非常大的数据集。重复距离矩阵计算的高效(记忆方式)功能和超大距离矩阵的分块
该函数接受一个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