[R] Extracting vectors from matrices

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Oct 27 10:21:01 CEST 2000

On Fri, 27 Oct 2000, Anon. (possibly Bob O'Hara with a broken
mailer) wrote:

> There is probably a simple and obvious answer to this, so sorry for
> wasting your time...
> I have a matrix of predictions from an proportional odds model (using
> the polr function in MASS), so the columns are the probabilities of the
> responses, and the rows are the data points.  I have another column with
> the observed responses, and I want to extract the probabilities for the
> observed responses.
> As a toy example, if I have 
> x <- matrix(c(1,2,3,4,5,6),2,3)
> y <- c(1,3)
> and I want to extract the numbers in x[1,1] and x[2,3] (the columns
> being indexed from y), what do I do?

I don't see a unique pattern to this, but is

 x[cbind(seq(along=y), y)]

what you had in mind?  The key is definitely matrix indexing.

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