[R] Re: I want to pull out an element from each of a list of matrices

Prof Brian D Ripley ripley at stats.ox.ac.uk
Sun Oct 15 22:00:13 CEST 2000

On Mon, 16 Oct 2000, Bill Venables wrote:

> At 18:26 14/10/00 +0100, Prof Brian D Ripley wrote:
> >On Sat, 14 Oct 2000, niels Waller wrote:
> >
> >> Dear colleagues,
> >> 
> >> I suspect there is a simple answer to this question -- but I cannot find
> it.
> >> 
> >> Suppose I have a list of matrices.  I want to pull out an element (such as
> >> row 1, col 2) from each matrix.  Do I need a loop to do this? Or is
> there an
> >> easy way to index this?
> >> 
> >> Let Z denote the list of matrices.  All matrices have the same order.  I
> >> want something like
> >>   Z[[.]][1,2]     (which of course will not work, but you get the idea)
> >
> >lapply(Z, function(x) x[1,2])
> or
> 	lapply(Z, "[", 1, 2)
> if you want to use the extractor function directly.  unlist() the result
> for a vector of results.

Yes, Peter D also said that.  BUT there is a bug in the current R
which means that the two are different, and the one I gave is I believe
more often correct. The difference only arises if the elements of Z have
classes, which they probably do not but we weren't told.  (Method dispatch
on primitives was only working if called by name, and lapply does not do
so: thanks to Luke Tierney for tracking the cause down.)  For R-devel the
two should be the same, and certainly are in my examples.

For unlist(lapply()) vs sapply: rumour has it the first is faster but I've
never seen convincing evidence under R and the second is certainly safer
and more powerful and easier to read in code.  So it was a deliberate
decision to choose the variants I did.

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