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.001371636
# 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) } 53.760 120.7850 134.7495 137.6515
#> { quantile(x, 0.5, na.rm = TRUE) } 200.124 223.7920 276.0054 239.1760
#> { median(x, na.rm = TRUE) } 122.277 145.8565 192.1249 161.0750
#> uq max neval
#> 159.6475 196.486 100
#> 364.4390 472.340 100
#> 278.7795 353.699 100