简体   繁体   中英

lookup using two columns with unique rows in R data.table

I am wondering if it is possible to use two columns to do a lookup in R data.table. Here is a little experiment that failed:

x <- data.table(A = c("a", "a", "b", "b", "c", "c"),
                D = c( 1,   2,   1,   2,   4,   5))
DT <- data.table(A = c("a", "a", "b", "b"),
                D = c( 1,   2,   1,   2))
setkey(DT, A, D)

DT[J(x$A, x$D), ]  # Same as below, thanks to ilir, I thought it returns an error previously
DT[J(x$A, x$D), , allow.cartesian=TRUE] 
# Return:
#    A D
# 1: a 1
# 2: a 2
# 3: b 1
# 4: b 2
# 5: c 4 # <- ideally (NA NA) or (c NA)
# 6: c 5 # <- ideally (NA NA) or (c NA)

In this experiment, rows in DT are unique, however, both columns have duplicated entries. When calling DT[J(x$A, x$D), ], what I want to do is to lookup table DT, thus I would expect the result only has entries in DT, however, this is clearly not the case.

Is there an effective way to do a lookup with two columns as keys?

Thanks to ilir, the following code works:

x <- data.table(A = c("a", "a", "b", "b", "c", "c"),
                D = c( 1,   2,   1,   2,   4,   5))
DT <- data.table(A = c("a", "a", "b", "b"),
                 D = c( 1,   2,   1,   2))
DT[, aux := 1L]
setkey(DT, A, D)
DT[J(x$A, x$D), ]

inx <- !is.na(DT[J(x$A, x$D), ]$aux)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM