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) } 100.525 107.7845 117.7460 116.0105
#> { quantile(x, 0.5, na.rm = TRUE) } 282.374 297.3975 337.7886 311.9105
#> { median(x, na.rm = TRUE) } 210.214 221.7405 256.2556 231.2100
#> uq max neval
#> 127.4215 142.314 100
#> 395.9515 488.818 100
#> 306.0455 391.172 100