简体   繁体   English

在 R 中使用 dist 计算和绘制成对距离

[英]Compute and plot pairwise distances using dist in R

I have a dataframe with 4 columns.我有一个包含 4 列的数据框。

set.seed(123)
df <- data.frame(A = round(rnorm(1000, mean = 1)),
           B = rpois(1000, lambda = 3),
           C = round(rnorm(1000, mean = -1)),
           D = round(rnorm(1000, mean = 0)))

I would like to compute the distances for every possible combination of my columns (AB, AC, AD, BC, BD, CD) at every row of my dataframe.我想在我的数据帧的每一行计算我的列(AB、AC、AD、BC、BD、CD)的每个可能组合的距离。 This would be the equivalent of doing df$A - df$B for every combination.这相当于对每个组合执行df$A - df$B

Can we use the dist() function to compute this efficiently as I have a very large dataset?由于我有一个非常大的数据集,我们可以使用dist()函数来有效地计算它吗? I would like to then convert the dist object into a data.frame to plot the results with ggplot2 .然后我想将 dist 对象转换为data.frame以使用ggplot2绘制结果。 Unless there is a good tidy version of doing the above.除非有一个很好的tidy版本来完成上述操作。

Many Thanks非常感谢

The closest I got was doing the below, but I am not sure to what the column names refer to.我得到的最接近的是执行以下操作,但我不确定列名指的是什么。

d <- apply(as.matrix(df), 1, function(e) as.vector(dist(e)))
t(d)

dist will compare every value in a vector to every other value in the same vector, so if you are looking to compare columns row-by-row, this is not what you are looking for. dist会将向量中的每个值与同一向量中的每个其他值进行比较,因此,如果您要逐行比较列,这不是您要查找的内容。

If you just want to calculate the difference between all columns pairwise, you can do:如果您只想成对计算所有列之间的差异,您可以执行以下操作:

df <- cbind(df, 
            do.call(cbind, lapply(asplit(combn(names(df), 2), 2), function(x) {
  setNames(data.frame(df[x[1]] - df[x[2]]), paste(x, collapse = ""))
})))

head(df)
#>   A B  C  D AB AC AD BC BD CD
#> 1 0 1 -2 -1 -1  2  1  3  2 -1
#> 2 1 1 -1  1  0  2  0  2  0 -2
#> 3 3 1 -2 -1  2  5  4  3  2 -1
#> 4 1 3  0 -1 -2  1  2  3  4  1
#> 5 1 3  0  1 -2  1  0  3  2 -1
#> 6 3 3  1  0  0  2  3  2  3  1

Created on 2022-06-14 by the reprex package (v2.0.1)reprex 包于 2022-06-14 创建 (v2.0.1)

Using base r:使用基数 r:

df_dist <- t(apply(df, 1, dist))
colnames(df_dist) <- apply(combn(names(df), 2), 2, paste0, collapse = "_")

If you really want to use a tidy-approach, you could go with c_across , but this also removes the names, and is much slower if your data is huge如果您真的想使用整洁的方法,则可以使用c_across ,但这也会删除名称,并且如果您的数据很大,则速度会慢得多

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

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