is_whole_number {timeplyr} | R Documentation |
Are all numbers whole numbers?
Description
Are all numbers whole numbers?
Usage
is_whole_number(x, tol = .Machine$double.eps, na.rm = TRUE)
Arguments
x |
A numeric vector. |
tol |
tolerance value. |
na.rm |
Should |
Details
This is a very efficient function that returns FALSE
if any number
is not a whole-number and TRUE
if all of them are.
Method
x
is defined as a whole number vector
if all numbers satisfy abs(x - round(x)) < tol
.
NA
handling
NA
values are handled in a custom way.
If x
is an integer, TRUE
is always returned even if x
has missing values.
If x
has both missing values and decimal numbers, FALSE
is always returned.
If x
has missing values, and only whole numbers and na.rm = FALSE
, then
NA
is returned.
Basically NA
is only returned if na.rm = FALSE
and
x
is a double vector of only whole numbers and NA
values.
Inspired by the discussion in this thread: check-if-the-number-is-integer
Value
A logical vector of length 1.
Examples
library(timeplyr)
library(dplyr)
# Has built-in tolerance
sqrt(2)^2 %% 1 == 0
is_whole_number(sqrt(2)^2)
is_whole_number(1)
is_whole_number(1.2)
x1 <- c(0.02, 0:10^5)
x2 <- c(0:10^5, 0.02)
is_whole_number(x1)
is_whole_number(x2)
# Somewhat more strict than all.equal
all.equal(10^9 + 0.0001, round(10^9 + 0.0001))
is_whole_number(10^9 + 0.0001)
# Can safely be used to select whole number variables
starwars %>%
select(where(is_whole_number))
# To reduce the size of any data frame one can use the below code
df <- starwars %>%
mutate(across(where(is_whole_number), as.integer))