as_integer_if_safe {hutilscpp} | R Documentation |
Coerce from double to integer if safe
Description
The same as as.integer(x)
but only if x
consists only of
whole numbers and is within the range of integers.
Usage
as_integer_if_safe(x)
Arguments
x |
A double vector. If not a double vector, it is simply returned without any coercion. |
Examples
N <- 1e6 # run with 1e9
x <- rep_len(as.double(sample.int(100)), N)
alt_as_integer <- function(x) {
xi <- as.integer(x)
if (isTRUE(all.equal(x, xi))) {
xi
} else {
x
}
}
bench_system_time(as_integer_if_safe(x))
#> process real
#> 6.453s 6.452s
bench_system_time(alt_as_integer(x))
#> process real
#> 15.516s 15.545s
bench_system_time(as.integer(x))
#> process real
#> 2.469s 2.455s
[Package hutilscpp version 0.10.5 Index]