Generalized ยท GitHub

The result of using between() in filtering is not equivalent to evaluating a conditional expression when working with ordered factors.

> (x <- data.frame(Visit = c("Discharge", "Month 3", "Month 6", "Month 12", "Month 20")))
      Visit
1 Discharge
2   Month 3
3   Month 6
4  Month 12
5  Month 20
> class(x$Visit)
[1] "character"

Now let's make it an ordered factor with assumed levels (used later for other operations):

> (x$Visit <- factor(x$Visit, levels = c("Baseline", "Discharge", "Month 3", "Month 6", "Month 12", "Month 20", "Premature"), ordered = TRUE))
[1] Discharge Month 3   Month 6   Month 12  Month 20
Levels: Baseline < Discharge < Month 3 < Month 6 < Month 12 < Month 20 < Premature

When filtering using the conjunction of conditions it works

> x %>% filter(Visit >= "Discharge" & Visit <= "Month 20")
      Visit
1 Discharge
2   Month 3
3   Month 6
4  Month 12
5  Month 20

When using the convenient between(), it doesn't

> x %>% filter(between(Visit, "Discharge", "Month 20"))
      Visit
1 Discharge
2  Month 12
3  Month 20

2 items are missing in the output.


R version 4.2.0 (2022-04-22 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)

packageVersion("dplyr")
[1] โ€˜1.1.1โ€™

Read the original on github.com โ†—