Reputation: 21
I am looking for rows that contain any of multiple variables in a data.table. my current code works, but is a bit messy:
#dt contains several columns, foo1, foo2, foo3, etc that have the same possible values
#Values I am searching for
bar <- ("a","b","c")
#current method
dt[foo1 %in% bar| foo2 %in% bar | foo3 %in% bar ...]
This method works, but I am wondering if there is a more efficient way to do this.
Upvotes: 2
Views: 71
Reputation: 388807
You can use lapply
with .SD
and Reduce
-
library(data.table)
dt[, .SD[Reduce(`|`, lapply(.SD, `%in%`, bar))]]
Upvotes: 3