[R] NA values in indexing

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Fri Mar 26 13:09:59 CET 2010


If you index a vector with a vector that has NA in it, you get NA back:

 > x=101:107
 > x[c(NA,4,NA)]
 [1]  NA 104  NA
 > x[c(4,NA)]
 [1] 104  NA

All well and good. ?"[" says, under NAs in indexing:

     When extracting, a numerical, logical or character ‘NA’ index
     picks an unknown element and so returns ‘NA’ in the corresponding
     element of a logical, integer, numeric, complex or character
     result, and ‘NULL’ for a list.  (It returns ‘00’ for a raw
     result.]

But if the indexing vector is all NA, you get back a vector of length
of your original vector rather than of your index vector:

 > x[c(NA,NA)]
 [1] NA NA NA NA NA NA NA

Maybe it's just me, but I find this surprising, and I can't see it
documented. Bug or undocumented feature? Apologies if I've missed
something obvious.

Barry

 sessionInfo()
R version 2.11.0 alpha (2010-03-25 r51407)
i686-pc-linux-gnu

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base



More information about the R-help mailing list