Filter rows in data.table with `by`

I would like to filter out a group that meets the following criteria. DTbrings unexpected results.

Input data

library(data.table)
library(dplyr)

dt <- data.table(
    logic = c(TRUE, TRUE, FALSE, TRUE, TRUE, TRUE),
    group = c("A" , "A",  "A"  , "B" , "B" , "B")
)

I would like to filter the group where the field values ​​are logic all TRUE.

Expected Behavior (by dplyr)

As you can see, it dplyrworks as expected and returns only values ​​withgroup = B

dt %>% 
  group_by(group) %>% 
  filter(all(logic))
# Source: local data table [3 x 2]
# Groups: group

#   logic group
# 1  TRUE     B
# 2  TRUE     B
# 3  TRUE     B

Unexpected behavior data.table

DT does not filter rows, or brings the entire table, or nothing.

dt[all(logic), group, by = group]
# Empty data.table (0 rows) of 2 cols: group,group

dt[all(.SD$logic), group,by = group]
#    group group
# 1:     A     A
# 2:     B     B
+4
source share
2 answers

You can use [as in

dt[, .SD[all(logic)], by = group]
#   group logic
#1:     B  TRUE
#2:     B  TRUE
#3:     B  TRUE
+4
source

We need to use if

dt[, if(all(logic)) .SD, by = group]
#    group logic
#1:     B  TRUE
#2:     B  TRUE
#3:     B  TRUE
+5
source

Source: https://habr.com/ru/post/1621086/


All Articles