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) } 53.729 110.3235 134.4818 139.5020
#> { quantile(x, 0.5, na.rm = TRUE) } 186.607 209.9310 289.9533 225.0535
#> { median(x, na.rm = TRUE) } 128.891 137.7345 203.2462 146.0120
#> uq max neval
#> 158.6600 201.138 100
#> 407.0085 568.944 100
#> 303.1640 683.914 100