Created
February 10, 2022 23:09
-
-
Save dantonnoriega/13a3c8a23c8ef03fb49f3112fdf476c2 to your computer and use it in GitHub Desktop.
a simple script that tests out different was of implementing the `if_any` logic in native 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(tidyverse) | |
dat <- as_tibble(mtcars) %>% | |
mutate(vs = as.character(vs), | |
am = as.character(am)) #just to make some non-numeric | |
dd0 <- dat %>% | |
select(where(is_numeric)) %>% | |
filter(if_any(disp:wt, ~ .x > 100)) | |
dd0 | |
library(data.table) | |
dd = data.table::as.data.table(dat) | |
rdx = dd[, .SD, .SDcols = is.numeric] | |
# Reduce lists using vectorized "or" ('|') | |
ii = rdx[, Reduce('|', lapply(.SD, '>', 100)), .SDcols = disp:wt] | |
## keep where any true | |
dd1 = rdx[ii] | |
identical(setDT(dd0), dd1) | |
# all at once | |
rdx[rdx[, Reduce('|', lapply(.SD, '>', 100)), .SDcols = disp:wt]] | |
# benchmark | |
library(data.table) | |
set.seed(1000) | |
n_m = expand.grid(n = c(3,12), m = c(2.5,100)*1e4) | |
# | |
results = mapply(function(n,m) { | |
my.df <- sample(1:80, m*n, replace=TRUE) | |
dim(my.df) <- c(m,n) | |
my.df <- as.data.frame(my.df) | |
names(my.df) <- c(LETTERS,letters)[1:n] | |
my.dt <- as.data.table(my.df) | |
bench::mark( | |
# using Reduce with lapply() | |
tm1 = my.dt[my.dt[, Reduce('|', lapply(.SD, '>', 75))]], | |
# using rowSums | |
tm2 = my.dt[rowSums(my.dt[, lapply(.SD, '>', 75)]) > 0], | |
# using apply with any() | |
tm3 = my.dt[apply(my.dt[, lapply(.SD, '>', 75)], 1, any)], | |
# dtplyr | |
tm4 = my.dt %>% dplyr::filter(if_any(.fns = ~ .x > 75)), | |
iterations=30L, | |
time_unit = 's' | |
) %>% | |
dplyr::mutate(n = n, m = m) | |
}, n = n_m$n, m = n_m$m, SIMPLIFY = FALSE) | |
dplyr::bind_rows(results) %>% | |
dplyr::select(n, m, expression, median, | |
total_time, `itr/sec`, mem_alloc, | |
n_itr, n_gc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The goal here was to extract all rows where a condition is TRUE for any one or more subset of columns—but using base
R
and puredata.table
.Basically, all but
apply
usingany
(tm3
) perform well and low cost.Reduce
using a logical operator like|
appears to be the most efficient.