Learn R Programming

timeplyr (version 1.1.0)

is_whole_number: Are all numbers whole numbers?

Description

Are all numbers whole numbers?

Usage

is_whole_number(x, tol = .Machine$double.eps^(2/3), na.rm = TRUE)

Value

A logical vector of length 1.

Arguments

x

A numeric vector.

tol

tolerance value.
The default is .Machine$double.eps^(2/3), an arbitrarily small tolerance.

na.rm

Should NA values be ignored? Default is TRUE.

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

Examples

Run this code
library(timeplyr)
library(dplyr)
# \dontshow{
.n_dt_threads <- data.table::getDTthreads()
.n_collapse_threads <- collapse::get_collapse()$nthreads
data.table::setDTthreads(threads = 1L)
collapse::set_collapse(nthreads = 1L)
# }
# 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))
# \dontshow{
data.table::setDTthreads(threads = .n_dt_threads)
collapse::set_collapse(nthreads = .n_collapse_threads)
# }

Run the code above in your browser using DataLab