按组计算一个观察值与所有其他观察值之间的差异

Calculate difference between one observation and all other observations by group

我正在尝试创建第一个观察结果与组内所有其他观察结果之间的距离。 A 组中的第一个观察值是 a1,B 组中的第一个观察值是 b1。

我想要 df 中的一个新列,“Euclidean”,它将包含每个观察值与按组计算的第一个观察值的距离。

 df <- data.table(Section = rep(c('A', 'B'), each = 4),
                                 ID = c('a1','a2','a3','a4','b1','b2','b3','b4'),
                                  x = c(5,10,15,15,10,15,30,25),
                                  y = c(12,10,8,4,6,8,16,24))

其中距离计算为欧氏[a1,a2] = sqrt((x1-x2)^2+(y1-y2)^2)。每组中的第一个值将是 0。我希望使用 dplyr 或 data.table 来完成此操作。非常感谢。

你的意思是这样的?

setDT(df)[, Distance := sqrt((x[1]-x)^2+(y[1]-y)^2), .(Section)]

两个解决方案dplyr

(1) 通过欧氏距离公式

df %>% group_by(Section) %>%
  mutate(Euclidean = sqrt((x - x[1])^2 + (y - y[1])^2))

(2) 按基函数 dist()

df %>% group_by(Section) %>%
  mutate(Euclidean = as.matrix(dist(cbind(x, y)))[1, ])

注:如果需要改变Minkowski距离的幂,第二种方式更灵活。如果你想要与其他观测值的距离,只需调整方括号中的数字即可。


输出:

#   Section ID        x     y Euclidean
#   <chr>   <chr> <dbl> <dbl>     <dbl>
# 1 A       a1        5    12      0   
# 2 A       a2       10    10      5.39
# 3 A       a3       15     8     10.8 
# 4 A       a4       15     4     12.8 
# 5 B       b1       10     6      0   
# 6 B       b2       15     8      5.39
# 7 B       b3       30    16     22.4 
# 8 B       b4       25    24     23.4