Created
January 31, 2022 14:58
-
-
Save AlbanSagouis/94a6a3eeff5e13fa4d0e74384625d7a3 to your computer and use it in GitHub Desktop.
microbenchmarking various ways of creating columns depending on values in another column of a data.table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(microbenchmark) | |
nrows <- 10^5 | |
tst1 <- data.table::data.table( | |
char = c("bb", "ds", "ok", "pb")[sample(1:4, nrows, replace = TRUE)] | |
) | |
tst2 <- tst3 <- tst4 <- tst5 <- tst6 <- data.table::copy(tst1) | |
microbenchmark( | |
times = 200L, | |
"base::ifelse" = tst1[, new := base::ifelse(char == "bb", "level1", | |
base::ifelse(char == "ds", "level2", | |
base::ifelse(char == "ok", "level3", "level4") | |
) | |
)], | |
"dplyr::if_else" = tst3[, new := dplyr::if_else(char == "bb", "level1", | |
dplyr::if_else(char == "ds", "level2", | |
dplyr::if_else(char == "ok", "level3", "level4") | |
) | |
)], | |
"data.table::fifelse" = tst2[, new := data.table::fifelse(char == "bb", "level1", | |
data.table::fifelse(char == "ds", "level2", | |
data.table::fifelse(char == "ok", "level3", "level4") | |
) | |
)], | |
"data.table::fcase" = tst4[, new := data.table::fcase( | |
char == "bb", "level1", | |
char == "ds", "level2", | |
char == "ok", "level3", | |
default = "level4" | |
)], | |
"base::match" = tst5[, new := c("level1", "level2", "level3", "level4")[base::match(char, c("bb", "ds", "ok", "pb"))]], | |
"data.table::chmatch" = tst6[, new := c("level1", "level2", "level3", "level4")[data.table::chmatch(char, c("bb", "ds", "ok", "pb"))]] | |
) | |
# base::match is the fastest for small (10^2) and large (10^7) columns. data.table::fcase is the most readable and allows using expressions/functions which match does not(?depends on what is put in the vector of values). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unit: milliseconds