[R] Best way to preallocate numeric NA array?

William Dunlap wdunlap at tibco.com
Fri Nov 27 18:33:41 CET 2009


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Rob Steele
> Sent: Thursday, November 26, 2009 8:03 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Best way to preallocate numeric NA array?
> 
> These are the ways that occur to me.
> 
> ## This produces a logical vector, which will get converted 
> to a numeric
> ## vector the first time a number is assigned to it.  That seems
> ## wasteful.
> x <- rep(NA, n)
> 
> ## This does the conversion ahead of time but it's still creating a
> ## logical vector first, which seems wasteful.
> x <- as.numeric(rep(NA, n))
> 
> ## This avoids type conversion but still involves two assignments for
> ## each element in the vector.
> x <- numeric(n)
> x[] <- NA
> 
> ## This seems reasonable.
> x <- rep(as.numeric(NA), n)
> 
> Comments?

I like the rep-based ones because they are more 'functional':
I can pass the output directly into another function.  If speed
is a big concern, I think that
   x <- rep.int(NA_real_, n)
may be the fastest but then it is not immediately apparent how
to do the same for integer or fancier classes.  (NA_real_ is
to the numeric class as NA_integer_ is to the integer class.)
Your last one, rep(as.<class>(NA), n), seems to me to be a
good compromise between readability and speed.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> 
> Thanks,
> Rob
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list