[R] indexing a vector
Thomas Lumley
tlumley at u.washington.edu
Tue May 8 17:55:07 CEST 2001
On Mon, 7 May 2001, Jeff Miller wrote:
> ----- Original Message -----
> From: Thomas Lumley <tlumley at u.washington.edu>
> Sent: Monday, May 07, 2001 1:38 PM
>
> > On Mon, 7 May 2001, David White wrote:
> >
> > >
> > > Dear R-List,
> > >
> > > How can one look up the row/column number for a given value in a matrix
> or
> > > data.frame? For example in a matrix that contains only unique values
> for
> > > in [,1] how can I find value x in [,1] and report its row number?
> > >
> >
> > match(x,matrix[,1])
> >
> > -thomas
>
> As a follow up to this question, what's the easiest way to
> find the column and row indicies for a specified value in a matrix,
> when you don't know which column it's in (as assumed above)?
>
> So if mymatrix <- matrix(c(3, 2, 4, 1), nrow = 2), what's the easiet
> way
> to see that the value 4 is in position (1, 2) ?
>
Well, a matrix is just a vector with dimensions, so you can do
pos<-match(4,mymatrix)
to find that 4 is in position 3 in the vector, and then the row number is
((pos - 1) %/% NROW(mymatrix)) +1
and the column number is
((pos-1) %% NROW(mymatrix))+1
since the numbers are stored one column at a time. If you have to do a
lot of these on the same matrix the functions row() and col() may help:
row(mymatrix)[match(4,mymatrix)]
and
col(mymatrix)[match(4,mymatrix)]
-thomas
Thomas Lumley Asst. Professor, Biostatistics
tlumley at u.washington.edu University of Washington, Seattle
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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