代码之家  ›  专栏  ›  技术社区  ›  ch.elahe

通过比较或当前两个数据帧的子集来查找ID

  •  0
  • ch.elahe  · 技术社区  · 7 年前

    我有两个数据帧,如下所示:

    > dput(df1)
    structure(list(Freq = c(1L, 1L, 1L, 1L, 0L, 0L, 2L, 1L), x = c(5L, 
    2L, 8L, 6L, 3L, 4L, 8L, 6L), y = c(1L, 4L, 2L, 3L, 5L, 6L, 8L, 
    8L), ID = 44:51), .Names = c("Freq", "x", "y", "ID"), class = "data.frame",row.names = c(NA, 
    -8L))
    > str(df1)
    'data.frame':   8 obs. of  4 variables:
     $ Freq: int  1 1 1 1 0 0 2 1
     $ x   : int  5 2 8 6 3 4 8 6
     $ y   : int  1 4 2 3 5 6 8 8
     $ ID  : int  44 45 46 47 48 49 50 51
    

    第二个是:

     > dput(df2)
     structure(list(Freq = c(1L, 1L, 1L, 1L), x = c(5L, 2L, 8L, 6L
     ), y = c(1L, 4L, 2L, 3L)), .Names = c("Freq", "x", "y"), class = "data.frame", row.names = c(NA, 
    -4L))
     > str(df2)
    'data.frame':   4 obs. of  3 variables:
     $ Freq: int  1 1 1 1
     $ x   : int  5 2 8 6
     $ y   : int  1 4 2 3
    

    我想从df1中找到df2的ID,因此我想要的输出是:

     44 45 46 47
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   pogibas    7 年前

    解决方案使用 base::merge()

    # Using OPs data
    merge(df1, df2)$ID
    # [1] 45 44 47 46
    

    在这里 merge 获取两个数据帧,并通过共享列名(即子集)将其合并 df1 通过 df2 ).