代码之家  ›  专栏  ›  技术社区  ›  A.Benson

使用R从两个数据表中匹配的值生成数据表

  •  0
  • A.Benson  · 技术社区  · 6 年前

    我有两个 data.tables (a和b)使用R,每行约10000行。每个 data.table 包含x、y和z三列。z值在每个列中都是唯一的 数据表 数据表

    这是我需要达到的一个例子。

    数据表a

    x    y      z
    a    1    100
    a    6    120
    c    5    234
    b    3    567
    d    8    645
    f    7    487
    

    x    y     z
    a    1    904
    b    6    120
    c    7    765
    e    3    567
    d    8    329
    a    0    638
    

    数据表c(新创建的数据表)应该如下所示

    x    y     z
    a    1    100
    d    8    645
    

    我看了这里( Matching values between data frames based on overlapping dates ),但这并没有让我达到我需要的地方。

    数据表 .

    library(data.table)
    
    x<-c("a","a","c","b","d","f")
    y<-c(1,6,5,3,8,7)
    z<-c(100,120,234,567,645,487)
    a<-data.frame(x,y,z)
    rm(x,y,z)
    
    x<-c("a","b","c","e","d","a")
    y<-c(1,6,7,3,8,0)
    z<-c(904,120,765,567,329,638)
    b<-data.frame(x,y,z)
    
    setDT(a)
    setDT(b)
    

    data.frames

    谢谢

    3 回复  |  直到 6 年前
        1
  •  2
  •   DanY    6 年前

    一个简单的 merge 会做到:

    merge(a, b, by=c("x","y"))
    

    默认情况下, 合并 all , all.x ,和 all.y 阿格斯,但在这里你不需要。

    z 数据表中的值 b

    merge(a, b[,.(x,y)], by=c("x","y"))
    
        2
  •  0
  •   Jon Spring    6 年前

    dplyr 方法:

    library(dplyr)
    c <- a %>% semi_join(b, by = c("x", "y"))
    
    > c
      x y   z
    1 a 1 100
    2 d 8 645
    
        3
  •  0
  •   nghauran    6 年前

    尝试:

    # Note that they should be different values of z for identical x and y
    # The following options assume that you also want to keep this information i.e. z values 
    # from a and b for matched columns x and y
    dplyr::inner_join(a, b, by = c("x", "y")) # option 1
    merge(a, b, by = c("x","y")) # option 2
    # option 3 using DT
    setkeyv(a, c("x","y"))
    setkeyv(b, c("x","y"))
    a[b, nomatch = 0]