Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

avoid use of dplyr::coalesce in favour of faster alternative dplyr::if_else #101

Closed
whipson opened this issue Jun 26, 2024 · 0 comments
Closed
Labels
enhancement New feature or request

Comments

@whipson
Copy link
Owner

whipson commented Jun 26, 2024

library(microbenchmark)
library(dplyr)

df_w_missing <- data.frame(
  r1 = 1:100,
  r2 = sample(letters, 100, replace = TRUE),
  r3 = sample(LETTERS, 100, replace = TRUE),
  r4 = Sys.time() - runif(100, -1e6, 1e6)
) |> 
  mutate(across(everything(), ~if_else(row_number() %in% sample(1:100, size = 25), NA, .x)))

microbenchmark(
  coalesce = {
    df_w_missing |> 
      mutate(
        r1 = coalesce(r1, 0),
        r2 = coalesce(r2, "a"),
        r3 = coalesce(r3, "A"),
        r4 = coalesce(r4, as.POSIXct("2024-05-01 10:00:00"))
      )
  },
  if_else = {
    df_w_missing |> 
      mutate(
        r1 = if_else(is.na(r1), 0, r1),
        r2 = if_else(is.na(r2), "a", r2),
        r3 = if_else(is.na(r3), "A", r3),
        r4 = if_else(is.na(r4), as.POSIXct("2024-05-01 10:00:00"), r4)
      )
  }
)

Unit: microseconds
     expr     min       lq     mean   median      uq      max neval
 coalesce 765.921 785.7035 960.2544 798.2905 811.595 8736.075   100
  if_else 680.518 696.0365 712.3824 708.9105 721.928  830.496   100
@whipson whipson added the enhancement New feature or request label Jun 26, 2024
whipson pushed a commit that referenced this issue Jul 30, 2024
@whipson whipson closed this as completed Jul 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant