Learn R Programming

kutils (version 0.93)

safeInteger: If a numeric variable has only integer values, then

Description

Users often accidentally create floating point numeric variables when they really mean integers, such as c(1, 2, 3), when they should have done c(1L, 2L, 3L). Before running as.integer() to coerce the variable, we'd rather be polite and ask the variable "do you mind being treated as if you are an integer?" This function checks to see if the variable is "close enough" to being an integer, and then coerces as integer. Otherwise, it returns NULL. And issues a warning.

Usage

safeInteger(x, tol = .Machine$double.eps, digits = 7, verbose = FALSE)

Arguments

x
a numeric variable
tol
Tolerance value. Defaults to Machine$double.eps. See details.
digits
Digits value passed to the zapsmall function. Defaults to 7.
verbose
Default FALSE: print warnings about x

Value

Either an integer vector or the original variable

Details

First, calculate absolute value of differences between x and as.integer(x). Second, compare the sum of those differences is smaller than tol, then x can reasonably be coerced to an integer.

Be careful with the return. The correct return value for variables that should not be coerced as integer is uncertain at this point. We've tested various strategies, sometimes returning FALSE, NULL, or just the original variable.

Examples

Run this code
x1 <- c(1, 2, 3, 4, 5, 6)
is.integer(x1)
is.double(x1)
is.numeric(x1)
(x1int <- safeInteger(x1))
is.integer(x1int)
is.double(x1int)
is.numeric(x1int)
x2 <- rnorm(100)
x2int <- safeInteger(x2)
head(x2int)
x3 <- factor(x1, labels = c(LETTERS[1:6]))
x3int <- safeInteger(x3)

Run the code above in your browser using DataLab