Grec001
Grec001

Reputation: 1121

How to meet multi condition with data.table in more graceful way?

Here is the toy sample including 2 character variables. I have another vector of two characters. By comparing one by one, I can get the result, but is there more graceful way of doing it?

set.seed(100)
DT <- data.table(V1 = LETTERS[sample(1:5, 10, replace = T)], 
                 V2 = LETTERS[sample(3:7, 10, replace = T)])
V1V2 = c("B", "G")
DT[V1 %in% V1V2[1] & V2 %in% V1V2[2]]
#    V1 V2
# 1:  B  G

Since we can directly get the row elements by apply with DT[apply(DT[,.(V1, V2)], 1, print)] There shall be a way to describe a multi-condition express in i.

I'm expecting something like:

DT[.(V1, V2) %in% V1V2]

but this seems not to be working.

Thanks for advice.

Upvotes: 3

Views: 69

Answers (2)

Jaap
Jaap

Reputation: 83215

Another option is to use the join-capabilities of :

setkey(DT, V1, V2)
DT[as.list(V1V2)]

or:

DT[as.list(V1V2), on = .(V1, V2)]

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 388982

We could use as.list to compare column-wise every element in V1V2

DT  == as.list(V1V2)

#       V1    V2
# [1,]  TRUE FALSE
# [2,]  TRUE  TRUE
# [3,] FALSE FALSE
# [4,] FALSE FALSE
# [5,] FALSE FALSE
# [6,] FALSE FALSE
# [7,] FALSE FALSE
# [8,]  TRUE FALSE
# [9,] FALSE FALSE
#[10,] FALSE FALSE

This compares V1V2[1] with 1st column of DT and V1V2[2] with second column.

Now select rows where all elements are TRUE

DT[rowSums(DT  == as.list(V1V2)) == ncol(DT), ]
#   V1 V2
#1:  B  G

Upvotes: 2

Related Questions