【问题标题】:How to calculate all pairwise difference for multiple varibles [closed]如何计算多个变量的所有成对差异[关闭]
【发布时间】:2021-10-29 22:57:25
【问题描述】:

我需要计算每个变量的所有成对差异(我的数据集中有 100 个):

然后我想总结(所有)每个成对和的值,并将它们排列在一个矩阵中。

【问题讨论】:

  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example。图片不是共享数据/代码的正确方式。
  • 你试过什么没用?

标签: r comparison pairwise


【解决方案1】:

如果我们需要matrix,我们可以使用outer

outer(seq_along(df1), seq_along(df1), FUN =
      Vectorize(function(i, j) sum(df1[[i]] - df1[[j]], na.rm = TRUE)))

-输出

 [,1]  [,2]  [,3]
[1,]   0.00 47.80 56.49
[2,] -47.80  0.00  8.69
[3,] -56.49 -8.69  0.00

或者如果我们不需要冗余比较,使用combn

combn(df1, 2, FUN = function(x) sum(x[[1]] - x[[2]], na.rm = TRUE))

-输出

[1] 47.80 56.49  8.69

数据

df1 <- structure(list(V1 = c(67.81, 65.33, 54.67, 53.2, 53.77, 52.66, 
50.77, 47.84, 46.33, 44.15), V2 = c(57.68, 56.58, 52.61, 49.74, 
49.28, 48.03, 46.15, 43.96, 42.76, 41.94), V3 = c(54.04, 54.34, 
52.36, 49.34, 48.93, 48.06, 46.21, 43.51, 42.15, 41.1)),
 class = "data.frame", row.names = c(NA, 
-10L))

【讨论】:

  • 我们也可以像as.numeric(dist(df1))这样使用dist,但它给出了很多数字!
  • @TarJae 它计算行之间的距离。也许transpose。此外,使用的默认方法是“欧几里得”。但我想 OP 只想要一个差异和总和
  • 很棒的答案!谢谢你来自哥伦比亚
【解决方案2】:

另一种方法是使用dist。在 akrun 的帮助下,我们得到:

dist(t(df1), method = "manhattan")
      V1    V2
V2 47.80      
V3 56.49  8.87

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2018-07-04
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多