Testing numeric variables for NA/NaN/Inf

In R, a numeric variable is either a number (like 0, 42, or -3.14), or one of 4 special values: NA, NaN, Inf or -Inf. It can be hard to remember how the is.x functions treat each of the special values, especially NA and NaN! The table below summarizes how each of these values is treated by different base R functions. Functions are listed in alphabetical order.

Function Typical number NA NaN Inf -Inf
is.double TRUE FALSE TRUE TRUE TRUE
is.finite TRUE FALSE FALSE FALSE FALSE
is.infinite FALSE FALSE FALSE TRUE TRUE
is.integer *1 FALSE FALSE FALSE FALSE
is.na FALSE TRUE TRUE FALSE FALSE
is.nan FALSE FALSE TRUE FALSE FALSE
is.null FALSE FALSE FALSE FALSE FALSE
is.numeric TRUE *2 TRUE TRUE TRUE

*1: is.integer can return TRUE or FALSE, depending on whether the number is an integer or not.

*2: R actually has different types of NAs (see here for more details). is.numeric(NA) returns FALSE, but is.numeric(NA_integer_) and is.numeric(NA_real_) return TRUE. Interestingly, is.numeric(NA_complex_) returns FALSE.

1 thought on “Testing numeric variables for NA/NaN/Inf

  1. Pingback: Distilled News | AnalytiXon

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s