简体   繁体   中英

Subset a data.table by matching columns of another data.table

I have been searching for a solution for subsetting a data table using matching values for certain columns in another data table.

Here is in example:

set.seed(2)

dt <- 
        data.table(a = 1:10, 
                   b = rnorm(10), 
                   c = runif(10), 
                   d = letters[1:10])

dt2 <- 
        data.table(a = 5:20, 
                   b = rnorm(16), 
                   c = runif(16), 
                   d = letters[5:20])

This is the result I need:

> dt2

 1:  5 -2.311069085 0.62512173 e
 2:  6  0.878604581 0.26030004 f
 3:  7  0.035806718 0.85907312 g
 4:  8  1.012828692 0.43748800 h
 5:  9  0.432265155 0.38814476 i
 6: 10  2.090819205 0.46150111 j

where I have the rows returned from the second data table where a and d match even though b and c may not. The real data are mutually exclusive, and I need to match on three columns.

We can use %in% to match the columns and subset accordingly.

dt2[a %in% dt$a & d %in% dt$d]
#    a           b         c d
#1:  5 -2.31106908 0.6251217 e
#2:  6  0.87860458 0.2603000 f
#3:  7  0.03580672 0.8590731 g
#4:  8  1.01282869 0.4374880 h
#5:  9  0.43226515 0.3881448 i
#6: 10  2.09081921 0.4615011 j

Here is an option using join and specifying the on

na.omit(dt2[dt[, c("a", "d"), with = FALSE], on = c("a", "d")])
#    a           b         c d
#1:  5 -2.31106908 0.6251217 e
#2:  6  0.87860458 0.2603000 f
#3:  7  0.03580672 0.8590731 g
#4:  8  1.01282869 0.4374880 h
#5:  9  0.43226515 0.3881448 i
#6: 10  2.09081921 0.4615011 j

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