[R] Array subscripting by names

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Mar 1 10:30:42 CET 2001


On Thu, 1 Mar 2001, BXC (Bendix Carstensen) wrote:

> I have:
>
> > version
>          _
> platform i386-pc-mingw32
> arch     x86
> os       Win32
> system   x86, Win32
> status
> major    1
> minor    2.1
> year     2001
> month    01
> day      15
> language R
> > m <- matrix( 1:6, 2, 3 )
> > rownames( m ) <- c( "a", "b" )
> > m
>   [,1] [,2] [,3]
> a    1    3    5
> b    2    4    6
> > m[ "a", ]
> [1] 1 3 5
> > m[ "b", ]
> [1] 2 4 6
> > m[ match( "c", rownames(m) ), ]
> [1] NA NA NA
> > m[ "c", ]
> Error: subscript out of bounds
>
> I would have guessed that the last two commands always produced the same
> result.
> Is this a bug or feature? If the latter is the case, what is the use of?

A feature.  Look at

> match( "c", rownames(m) )
[1] NA
> m[NA, ]
   [,1] [,2] [,3]
NA   NA   NA   NA
NA   NA   NA   NA
> m[as.numeric(NA), ]
[1] NA NA NA

to see what is going on.  Indexing by NA (logical or numeric) can
occasionally be useful.

Most of the time I think you want

> m[ match( "c", rownames(m), nomatch=0 ), ]
>      [,1] [,2] [,3]

to omit missing names.

Brian

-- 
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 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list