Present since hutils 1.2.0.

all_same_sign(x)

Arguments

x

A numeric vector.

Value

TRUE if all elements of x have the same sign. Zero is a separate sign from positive and negative. All vectors of length-1 or length-0 return TRUE, even if x = NA, (since although the value is unknown, it must have a unique sign), and non-numeric x.

Examples

all_same_sign(1:10)
#> [1] TRUE
all_same_sign(1:10 - 1)
#> [1] FALSE
all_same_sign(0)
#> [1] TRUE
all_same_sign(NA)
#> [1] TRUE
all_same_sign(c(NA, 1))
#> [1] NA
all_same_sign("surprise?")
#> [1] TRUE
all_same_sign(c(0, 0.1 + 0.2 - 0.3))
#> [1] FALSE
if (requireNamespace("microbenchmark", quietly = TRUE)) { library(microbenchmark) microbenchmark(base = length(unique(sign(1:1e5), nmax = 3)) == 1L, all_same_sign(1:1e5)) }
#> Unit: microseconds #> expr min lq mean median uq max neval cld #> base 1989.9 2026.0 2304.361 2039.65 2071.8 9020.1 100 b #> all_same_sign(1:1e+05) 86.3 87.7 100.670 96.25 104.5 173.1 100 a
# Unit: microseconds # expr min lq mean median uq max neval cld # base 2012 2040 2322 2047 2063 9324 100 b # all_same_sign(1:1e+05) 86 86 94 89 93 290 100 a