paljenczy
paljenczy

Reputation: 4899

data.table - check if one column is in another (list) column

I have a data table with a column containing lists. I want to check if another column is present in the list column as.

library(data.table)
dt <- data.table("a" = 1:3, "b" = list(1:2, 3:4, 5:6))

I tried:

dt[, is_a_in_b := a %in% b]
dt
#    a   b is_a_in_b
# 1: 1 1,2     FALSE
# 2: 2 3,4     FALSE
# 3: 3 5,6     FALSE

which does not give the correct result. The desired table would be

dt
#    a   b is_a_in_b
# 1: 1 1,2      TRUE
# 2: 2 3,4     FALSE
# 3: 3 5,6     FALSE

Upvotes: 2

Views: 753

Answers (1)

paljenczy
paljenczy

Reputation: 4899

You can use the mapply function with applying the function %in% to two vectors: a and b. In effect it takes a pair of vectors (lists) and produces for every index ix the result of a[ix] %in% b[[ix]].

dt[, is_a_in_b := mapply('%in%', a, b)]

> dt
   a   b is_a_in_b
1: 1 1,2      TRUE
2: 2 3,4     FALSE
3: 3 5,6     FALSE

Upvotes: 2

Related Questions