Slightly faster than quantile
with
na.rm=TRUE
. The internal implementation uses the 'C++' function
std::nth_element
, which is significantly faster than base R
implementation when the length of input x
is less than 1e7
.
Examples
# create input x with NAs
x <- rnorm(10000)
x[sample(10000, 10)] <- NA
# compute median
res <- fastquantile(x, 0.5)
res
#> [1] 0.01298609
# base method
res == quantile(x, 0.5, na.rm = TRUE)
#> 50%
#> TRUE
res == median(x, na.rm = TRUE)
#> [1] TRUE
# Comparison
microbenchmark::microbenchmark(
{
fastquantile(x, 0.5)
},{
quantile(x, 0.5, na.rm = TRUE)
},{
median(x, na.rm = TRUE)
}
)
#> Unit: microseconds
#> expr min lq mean median
#> { fastquantile(x, 0.5) } 63.077 117.5940 125.6712 127.5175
#> { quantile(x, 0.5, na.rm = TRUE) } 265.796 282.1455 320.7031 290.1505
#> { median(x, na.rm = TRUE) } 199.943 212.5310 244.7711 219.1885
#> uq max neval
#> 137.1810 175.306 100
#> 311.5700 465.377 100
#> 232.2075 386.189 100