【问题标题】:R Generate non repeating pairs in dataframeR在数据框中生成非重复对
【发布时间】:2016-03-16 22:57:11
【问题描述】:

所以目的是通过取距离来比较每个ID和其他ID。

考虑以下数据框Df

ID AN     AW
a  white  green
b  black  yellow
c  purple gray
d  white  gray

为了比较,我需要一个如下所示的组合:

ID   AN     AW    ID2   AN2    AW2
a  white  green   b   black  yellow
a  white  green   c   purple gray
a  white  green   d   white  gray
b   black  yellow c   purple gray 
b   black  yellow d   white  gray
c   purple gray   d   white  gray

基本上,我正在尝试实现所有组合,以获取属于每个 ID 的特征之间的距离。

这里我真的不知道现在如何开始。有什么见解吗?我可以使用 R 中的哪些工具?

【问题讨论】:

  • 使用ID:t(combn(unique(Df$ID), 2))

标签: r dataframe


【解决方案1】:

使用组合和匹配的一种可能解决方案。

ids <- combn(unique(df$ID), 2)
data.frame(df[match(ids[1,], df$ID), ], df[match(ids[2,], df$ID), ])

#     ID     AN     AW ID.1   AN.1   AW.1
# 1    a  white  green    b  black yellow
# 1.1  a  white  green    c purple   gray
# 1.2  a  white  green    d  white   gray
# 2    b  black yellow    c purple   gray
# 2.1  b  black yellow    d  white   gray
# 3    c purple   gray    d  white   gray

【讨论】:

  • 更简单:data.frame(Df[combn(Df$ID, 2)[1,],], Df[combn(Df$ID, 2)[2,],])
  • 仅当因子的水平与右行对应的顺序正确时才有效。例如。如果我们添加 droplevels(ids[,2]) 你不会得到你想要的结果
  • 谢谢你们,现在我的口袋里有了一些新工具!
  • @NBATrends 这在这种情况下工作得很好,但是当我试图在一个大数据帧2328439 signatures of 11 variables 上实现它时,我得到了这个错误。 Error in combn(unique(signatures$uniqueid), 2) : n &lt; m。有什么想法吗?
  • 不确定,可能值得提出一个新问题
猜你喜欢
  • 2016-09-03
  • 2010-12-04
  • 2010-12-15
  • 2011-01-05
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多