相关疑难解决方法(0)

来自两个独立数据帧的距离矩阵

我想创建一个矩阵,其中包含从一个数据帧到另一个数据帧的行的欧几里德距离.例如,假设我有以下数据框:

a <- c(1,2,3,4,5)
b <- c(5,4,3,2,1)
c <- c(5,4,1,2,3)
df1 <- data.frame(a,b,c)

a2 <- c(2,7,1,2,3)
b2 <- c(7,6,5,4,3)
c2 <- c(1,2,3,4,5)
df2 <- data.frame(a2,b2,c2)
Run Code Online (Sandbox Code Playgroud)

我想创建一个矩阵,其中df1中每行的距离与df2的行相距.

因此矩阵[2,1]应该是df1 [2,]和df2 [1,]之间的欧氏距离.矩阵[3,2] df [3,]和df2 [2,]等之间的距离.

有谁知道如何实现这一目标?

r matrix euclidean-distance dataframe

4
推荐指数
1
解决办法
1334
查看次数

高效(记忆)功能,用于重复距离矩阵计算和超大距离矩阵的分块

我想知道是否有人可以查看以下代码和最小示例并提出改进建议 - 特别是关于使用非常大的数据集时代码的效率.

该函数采用data.frame并将其按分组变量(因子)拆分,然后计算每个组中所有行的距离矩阵.

我不需要保持距离矩阵 - 只有一些统计数据,即均值,直方图......,然后它们可以被丢弃.

我对内存分配等知之甚少,我想知道最好的方法是什么,因为我将使用每组10.000-100,000个案例.任何想法将不胜感激!

此外,在遇到严重的内存问题时,将bigmemory或其他大型数据处理包包含在函数中的最不痛苦的方法是什么?

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 …
Run Code Online (Sandbox Code Playgroud)

memory-management r distance matrix chunking

3
推荐指数
1
解决办法
3433
查看次数