[R] Indexing, and using an empty string as a name

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Nov 7 08:51:02 CET 2007


On Tue, 6 Nov 2007, Charilaos Skiadas wrote:

> Hello all,
>
> I ran into the following, to me unexpected, behavior. I have (for
> reasons that don't necessarily pertain to the question at hand, hence
> I won't go into them) the need/desire to use an empty string for the
> name of a vector entry.

The 'R Languge Definition' says

   The string "" is treated specially: it indicates `no name' and matches
   no element (not even those without a name).

and from ?names

   The name \code{""} is special: it is used to indicate that there is no
   name associated with an element of a (atomic or generic) vector.
   Subscripting by \code{""} will match nothing (not even elements which
   have no name).

so it should perhaps have been expected.


> Perhaps I did not read ?"[" very carefully,
> but it seems to me that he following lines should return "1" at the end:
>
> x<-1:4
> names(x) <- c("","a","b","c")
> x[""]
>
>
> Instead, they return NA. Could anyone provide an explanation for this
> behavior?

You can do

> x[[""]]
[1] 1

(which is arguably a bug given the quotes above) or

x[match("", names(x))]


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list