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.001544295
# 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) } 83.967 145.7415 157.2159 155.8210
#> { quantile(x, 0.5, na.rm = TRUE) } 258.773 282.7030 333.0872 299.0085
#> { median(x, na.rm = TRUE) } 181.579 201.4360 251.6051 215.7425
#> uq max neval
#> 177.1010 224.630 100
#> 401.2340 568.752 100
#> 339.3735 376.994 100