[Rd] Possible inconsistency between `as.complex(NA_real_)` and the docs

Davis Vaughan d@v|@ @end|ng |rom po@|t@co
Fri Apr 14 18:29:32 CEST 2023


Hi all,

Surprisingly (at least to me), `as.complex(NA_real_)` results in
`complex(real = NA_real_, imaginary = 0)` rather than `NA_complex_`.

It seems to me that this goes against the docs of `as.complex()`,
which say this in the Details section:

"Up to R versions 3.2.x, all forms of NA and NaN were coerced to a
complex NA, i.e., the NA_complex_ constant, for which both the real
and imaginary parts are NA. Since R 3.3.0, typically only objects
which are NA in parts are coerced to complex NA, but others with NaN
parts, are not. As a consequence, complex arithmetic where only NaN's
(but no NA's) are involved typically will not give complex NA but
complex numbers with real or imaginary parts of NaN."

To me this suggests that `NA_real_`, which is "NA in parts", should
have been coerced to "complex NA".

`NA_integer_` is actually coerced to `NA_complex_`, which to me is
further evidence that `NA_real_` should have been as well.

Here is the original commit where this behavior was changed in R 3.3.0:
https://github.com/wch/r-source/commit/4a4c2052e5a541981a249d4fcf92b54ca7f0a2df

```
# This is expected, based on the docs
x <- as.complex(NaN)
Re(x)
#> [1] NaN
Im(x)
#> [1] 0

# This is not expected. The docs say:
# "Since R 3.3.0, typically only objects which are NA in parts are
coerced to complex NA"
# but that doesn't seem true for `NA_real_`.
x <- as.complex(NA_real_)
Re(x)
#> [1] NA
Im(x)
#> [1] 0

# It does seem to be the case for `NA_integer_`
x <- as.complex(NA_integer_)
Re(x)
#> [1] NA
Im(x)
#> [1] NA
```

Thanks,
Davis Vaughan



More information about the R-devel mailing list