【问题标题】:R - get all pairs of values with same IDR - 获取所有具有相同 ID 的值对
【发布时间】:2016-03-13 23:50:58
【问题描述】:

我无法以我需要的方式处理数据。采取以下示例数据框:

df <- data.frame(id=factor(c(1,1,1,2,2,3)), person=c('P1','P2','P3','P4','P1','P3'))

  id person
1  1     P1
2  1     P2
3  1     P3
4  2     P4
5  2     P1
6  3     P3

我想生成一个数据框,其中包含每个id 中每个可能的person 对,所有 包括独特的排列(即P1-P2P2- P1 是唯一的)。例如:

  id  person1  person2
1  1       P1       P2
2  1       P1       P3
3  1       P2       P1
4  1       P2       P3
5  1       P3       P1
6  1       P3       P2
7  2       P4       P1
8  2       P1       P4
9  3       P3       NA

注意:注意id'3'和person'P3'没有任何其他匹配的人,因此在最终数据框的person2列中有一个NA。尽管这是非常需要的,但如果它不可能或非常困难,我将采取忽略 id 3 或仅将 P3 值与其自身匹配的响应(例如,P3-P3)。

如果我没有很好地表达这一点,请告诉我,我很乐意详细说明。谢谢!

【问题讨论】:

    标签: r dplyr plyr reshape data-manipulation


    【解决方案1】:

    您可以使用id 作为键,对df 执行merge。但是,它会显示与自己匹配的人(例如P1-P1P2-P2 等)。之后您可以删除这些行。

    # Data in question
    df <- data.frame(id=factor(c(1,1,1,2,2,3)), 
                     person=c('P1','P2','P3','P4','P1','P3'))
    
    # Merge with itself
    df2 <- merge(df, df, by = "id", suffixes = c("1", "2"), all.x = TRUE)
    
       id person1 person2
    1   1      P1      P1
    2   1      P1      P2
    3   1      P1      P3
    4   1      P2      P1
    5   1      P2      P2
    6   1      P2      P3
    7   1      P3      P1
    8   1      P3      P2
    9   1      P3      P3
    10  2      P4      P4
    11  2      P4      P1
    12  2      P1      P4
    13  2      P1      P1
    14  3      P3      P3
    
    # Remove self matches
    subset(df2, person1 != person2)
    
       id person1 person2
    2   1      P1      P2
    3   1      P1      P3
    4   1      P2      P1
    6   1      P2      P3
    7   1      P3      P1
    8   1      P3      P2
    11  2      P4      P1
    12  2      P1      P4
    

    【讨论】:

      【解决方案2】:

      您可以使用合并功能将 data.frame 合并到自身,如下所示:

      new.df=unique(merge(df, df, by='id'))
      

      使用子集函数来排除两列中同一个人的任何内容:

      final.df=subset(new.df, person.x!=person.y)
      

      【讨论】:

        猜你喜欢
        • 2015-09-02
        • 1970-01-01
        • 1970-01-01
        • 2019-12-10
        • 2017-10-29
        • 2020-01-05
        • 1970-01-01
        • 2020-06-19
        • 2021-05-24
        相关资源
        最近更新 更多