繁体   English   中英

计算R中不同组观测的成对欧氏距离?

[英]Calculating pairwise euclidean distances for observations from different groups in R?

我有一个数据框,其中包含三个变量(V1到V3)的观察结果,分为3组:

  V1   V2   V3 group
0.59 0.78 0.91     1
0.72 0.91 0.73     2
1.31 1.21 0.90     3
4.32 1.53 3.20     2
....

我想计算观察之间的欧氏距离。 在所有观测值之间计算成对距离很​​容易:

df %>% 
    select(-group) %>% 
    dist()

但我也有兴趣计算成对距离(a)仅在不属于同一组的观察之间的同一组(b)中的观察之间(例如,在组1中的每个观察与组2和3中的所有观察之间)。

对于(a),我可以这样做:

for (x in unique(df$group){
    df %>%
    filter(group == x) %>%
    select(-group) %>% 
    dist()
}

并将结果加在一起; 但我不太清楚如何完成(b)。 应如何做到最好?

谢谢!

如何在变量组合矩阵中应用类似于函数的函数:

library(dplyr)

## define the data frame
df = as.data.frame(cbind(c(.59, .72, 1.31, 4.32),
           c(.78, .91, 1.21, 1.52),
           c(.91, .73, .9, 3.2),
           c(1,2,3,2)), stringsAsFactors = FALSE)

names(df) = c("V1", "V2", "V3", "group")

## generate a matrix with the unique combinations of groups
combinations = combn(x = unique(df$group), m = 2)

## apply a function over the matrix of group combinations to determine
## the distance between the variable observations
distlist = lapply(seq(from = 1, to = ncol(combinations)), function(i){

  tmpdist = df %>% filter(group %in% combinations[,i]) %>%
    select(-group) %>%
    dist()

  return(cbind(combinations[1,i], combinations[2,i], tmpdist))

})

## combine the list into a dataframe 
dists = do.call(rbind, distlist)

names(dists) = c("group1", "group2", "dist")

这是一种通过给定条件分割距离和提取的计算方法。

##  distance as a matrix
d_m <- df %>% 
  select(-group) %>% 
  dist() %>% 
  as.matrix()

##  combination of groups
cb_g <- combn(df$group, m= 2)
##  combination of indices
cb_i <- combn(1:length(df$group), m= 2) 

##  extract the values that fit to given conditions
corr_same_grp <- apply(cb_g, 2, function(x) x[1] == x[2]) %>%  # same groups
  { cb_i[, ., drop= F] } %>%           # get indices
  apply(2, function(x) d_m[x[2], x[1]])

corr_diff_grp <- apply(cb_g, 2, function(x) x[1] != x[2]) %>%  # different groups 
  { cb_i[, ., drop= F] } %>%           # get indices
  apply(2, function(x) d_m[x[2], x[1]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM