[Rd] Generate NA of specified type

Hadley Wickham hadley at rice.edu
Wed May 5 18:25:48 CEST 2010


> What about NAof <- function(x) as(NA, class(x))?
>

That's pretty close, but it doesn't fail nicely for non-atomics:

> as(NA, class(Sys.Date()))
Error in as(NA, class(Sys.Date())) :
  no method or default for coercing "logical" to "Date"

vs.

> as.Date(NA)
[1] NA

But I'm probably being too fussy (especially since I didn't ask for
that in my original post ;).  I'm currently using this:

NAof <- function(x) {
  length(x) <- 1
  is.na(x) <- TRUE
  x
}

It's rather lacking in elegance :(

Hadley


-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



More information about the R-devel mailing list