J. Bowman
J. Bowman

Reputation: 21

Checking Presence of Same Value Across Multiple Variables

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

Answers (2)

akrun
akrun

Reputation: 886938

We may also use

dt[dt[, Reduce(`|`, lapply(.SD, `%chin%`, bar))]]

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388807

You can use lapply with .SD and Reduce -

library(data.table)

dt[, .SD[Reduce(`|`, lapply(.SD, `%in%`, bar))]]

Upvotes: 3

Related Questions