Data. Table Fcase Versus Dplyr Case_When

The following code throws an error when evaluating the line with fcase.

library(data.table)
library(dplyr)
tbl.test <- data.table(x = 0.5*(1:2))
tbl.test[, .(fcase(x < 1, x+1, 
                 default = x))]

tbl.test[, .(case_when(x < 1 ~ x+1, 
                        TRUE ~ x)
             )]

As I use case_when in this way (for most complex stuff ..), I wanted to switch to fcase, hoping a real gain in performance ..

Does anyone see where the devil hide with this usage of fcase ? The point is that I can't use a column of my table as default value with fcase ..

3

1 Answer

You don't explicitly state a question, but I assume you'd like to know if there's a way to use a vectorized default value with fcase(). One way to do that would be to construct a vector of TRUEs of equal length to your other conditions as the last element, similarly to how case_when() works:

library(data.table)
library(dplyr)

set.seed(123)

tbl.test <- data.table(x = rnorm(1e6))

bench::mark(
  fcase = tbl.test[, .(fcase(x < 1, x + 1, rep_len(TRUE, length(x)), x))],
  case_when = tbl.test[, .(case_when(x < 1 ~ x + 1, TRUE ~ x))]
)
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 2 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 fcase        16.5ms   24.3ms     33.3     36.1MB     43.1
#> 2 case_when   146.4ms  147.9ms      6.60   129.9MB     28.1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest