theArun theArun - 2 months ago 6
R Question

Apply boolean function to column in data.table in R

I am looking to find the "AND" or "OR" of all the elements by grouping based on column

a
in a data.table. I haven't been able to find any library that I could use. Any suggestions would be great. Thanks.

set.seed(1)
dt <- data.table(a = sample(seq.int(1,100,1),100,replace =TRUE),b = sample(c(TRUE,FALSE),100,replace = TRUE))
# head(dt)
# a b
# 1: 27 FALSE
# 2: 38 TRUE
# 3: 58 TRUE
# 4: 91 FALSE
# 5: 21 FALSE
# 6: 90 TRUE

Answer

Perhaps we need

dt[, if(all(b)) .SD , by = a]
dt[, if(any(b)) .SD ,by = a]

If we need to extract the 'a' elements

dt[, if(all(b)) a, by = a]$V1