Keyed lookup on data.table without 'with'

后端 未结 4 2078
执笔经年
执笔经年 2020-12-02 00:35

I have a data.table structure like so (except mine is really huge):

dt <- data.table(x=1:5, y=3:7, key=\'x\')

I want to loo

4条回答
  •  被撕碎了的回忆
    2020-12-02 01:07

    Setting a key is not required and it's faster:

    dt[eval(dt[, x %in% ..x])]
    
       x y
    1: 3 5
    2: 4 6
    

    Benchmark with the previously posted answers

    microbenchmark(dt[eval(dt[, x %in% ..x])],
                   dt[J(get('x', parent.frame(3)))],
                   dt[eval(list(x))],
                   dt[eval(J(x))],
                   dt[eval(.(x))],
                   merge(dt, data.table(x)),
                   times = 100L)
    
    Unit: microseconds
                                      expr    min      lq     mean  median      uq    max neval
          dt[eval(dt[, x %in% ..x])]  486.1  500.60  518.529  503.70  512.65 1238.0   100
    dt[J(get("x", parent.frame(3)))]  837.3  853.25  891.424  860.00  868.30 1675.3   100
                   dt[eval(list(x))]  831.8  842.70  929.521  851.95  859.85 3878.3   100
                      dt[eval(J(x))]  833.8  845.50  948.535  856.00  870.00 4599.2   100
                      dt[eval(.(x))]  828.6  846.40  871.054  851.75  859.35 1985.6   100
            merge(dt, data.table(x)) 1766.0 1804.70 1907.617 1819.95 1870.95 3123.1   100
    

提交回复
热议问题