代码之家  ›  专栏  ›  技术社区  ›  Andrea Neri

提取数据行。表中的其他数据行。表[副本]

  •  2
  • Andrea Neri  · 技术社区  · 7 年前

    我找不到任何答案,但我认为这很容易做到。

    我有这些数据。表:

    DT = expand.grid(Season = c("Winter","Spring","Summer","Fall"),
                     Station = c("A","B","C"),
                     Group = c("1","2","3","4"))
    DT$Value = seq(1,length(DT[,1]),1)
    DT = data.table(DT)
    

    我想获得 DT 根据其他数据。表:

    indexTable = data.table(Season = c("Winter","Spring","Spring"),
                            Station = c("B","B","A"),
                            Group = c("1","2","3"))
    

    基本上我只想要 DT公司 包含在 indexTable 。预期结果如下表所示:

    expectedTable = data.table(Season = c("Winter","Spring","Spring"),
                               Station = c("B","B","A"),
                               Group = c("1","2","3"),
                               Value = c(5,18,26))
    

    我试图通过此代码获得:

    tryTable = DT[DT$Station %in% indexTable$Station &
                  DT$Season %in% indexTable$Season &
                  DT$Group %in% indexTable$Group,]
    

    这不仅给了我想要的3行,还给了其他几行 DT公司

    我做错了什么?有没有简单的方法 expectedTable 使用数据。表索引符号(例如使用 setkey ?)

    1 回复  |  直到 7 年前
        1
  •  4
  •   SymbolixAU Adam Erickson    7 年前

    您正在寻找两个表的内部联接。

    DT[
        indexTable
        , on = c("Season", "Station", "Group")
        , nomatch = 0
    ]
    
       Season Station Group Value
    1: Winter       B     1     5
    2: Spring       B     2    18
    3: Spring       A     3    26
    

    参考