Skip to content

Commit 6118f02

Browse files
authored
Filtering by negated logical column (#212)
Fixes #211
1 parent 5a084b0 commit 6118f02

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# dtplyr (development version)
22

3+
4+
* `filter()` works for negated logical columns (@mgirlich, @211).
5+
36
* speed up `slice_min()` and `slice_max()` after `group_by()` (@mgirlich, #216).
47

58
* `slice_max()` now works when ordering by a character column (@mgirlich, #218).

R/step-subset-filter.R

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
filter.dtplyr_step <- function(.data, ..., .preserve = FALSE) {
2323
dots <- capture_dots(.data, ..., .j = FALSE)
2424

25-
if (length(dots) == 1 && is_symbol(dots[[1]])) {
25+
if (filter_by_lgl_col(dots)) {
2626
# Suppress data.table warning when filtering with a logical variable
2727
i <- call2("(", dots[[1]])
2828
} else {
@@ -32,6 +32,20 @@ filter.dtplyr_step <- function(.data, ..., .preserve = FALSE) {
3232
step_subset_i(.data, i)
3333
}
3434

35+
filter_by_lgl_col <- function(dots) {
36+
if (length(dots) > 1) {
37+
return(FALSE)
38+
}
39+
40+
dot <- dots[[1]]
41+
if (is_symbol(dot)) {
42+
return(TRUE)
43+
}
44+
45+
# catch expressions of form `!x`
46+
is_call(dot, name = "!", n = 1) && is_symbol(dot[[2]])
47+
}
48+
3549
# exported onLoad
3650
filter.data.table <- function(.data, ...) {
3751
.data <- lazy_dt(.data)

tests/testthat/test-step-subset-filter.R

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,20 @@ test_that("can filter by value", {
2121
)
2222
})
2323

24+
test_that("can filter with logical columns", {
25+
dt <- lazy_dt(data.table(x = c(TRUE, FALSE)), "DT")
26+
27+
expect_equal(
28+
dt %>% filter(x) %>% show_query(),
29+
expr(DT[(x)])
30+
)
31+
32+
expect_equal(
33+
dt %>% filter(!x) %>% show_query(),
34+
expr(DT[(!x)])
35+
)
36+
})
37+
2438

2539
test_that("inlines external variables", {
2640
dt <- lazy_dt(data.table(x = 1), "DT")

0 commit comments

Comments
 (0)