R Programming By Example
上QQ阅读APP看书,第一时间看更新

Special values

There are a few special values in R. The NA values are used to represent missing values, which stands for not available. If a computation results in a number that is too big, R will return Inf for a positive number and -Inf for a negative number, meaning positive and negative infinity, respectively. These are also returned when a number is pided by 0. Sometimes a computation will produce a result that makes little sense. In these cases, we will get a NaN, which stands for not a number. And, finally, there is a null object, represented by NULL. The symbol NULL always points to the same object (which is a data type on its own) and is often used as a default argument in functions to mean that no value was passed through. You should know that NA, Inf, -Inf, NaN, and NULL are not substitutes for each other.

There are specific NA values for numerics, characters, and logicals, but we will stick to the simple NA, which is internally treated as a logical.

In the following example, you can see how these special values behave when used among themselves in R. Note that 1 / 0 results in Inf, 0 / 0, Inf - Inf, and Inf / Inf results in undefined represented by NaN, but Inf + Inf, 0 / Inf, and Inf / 0, result in Inf, 0, and Inf, respectively. It's no coincidence that these results resemble mathematical definitions. Also note that any operation including NaN or NA will also result in NaN and NA, respectively:

1 / 0
#> [1] Inf -1 / 0
#> [1] -Inf 0 / 0
#> [1] NaN Inf + Inf
#> [1] Inf Inf - Inf
#> [1] NaN Inf / Inf
#> [1] NaN Inf / 0
#> [1] Inf 0 / Inf
#> [1] 0 Inf / NaN
#> [1] NaN Inf + NA
#> [1] NA