[R] retrieving matrix elements by giving pairs of row AND column numbers?

Werner Wernersen pensterfuzzer at yahoo.de
Wed Oct 22 20:58:48 CEST 2008


Many thanks, Greg!

Now I know why I thought that this does not work: I probably tried it with the string names of the columns and rows instead of their numbers. The former does not work (I think).

Thanks to all again!
  Werner



----- Ursprüngliche Mail ----
Von: Greg Snow <Greg.Snow at imail.org>
An: Werner Wernersen <pensterfuzzer at yahoo.de>; "r-help at stat.math.ethz.ch" <r-help at stat.math.ethz.ch>
Gesendet: Mittwoch, den 22. Oktober 2008, 19:37:28 Uhr
Betreff: RE: [R] retrieving matrix elements by giving pairs of row AND column numbers?

Subscript using a 2 column matrix with the rows in the first column and the cols in the 2nd column, e.g.:

> x <- matrix(1:9, 3)
> x[ cbind( c(1,2,3), c(3,2,1) ) ]
[1] 7 5 3

Hope this helps,

--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Werner Wernersen
> Sent: Wednesday, October 22, 2008 12:24 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] retrieving matrix elements by giving pairs of row AND
> column numbers?
>
> Hi,
>
> this is probably a very trivial question but I can't figure out the
> right terms to find the solution in the list archive.
>
> I have a matrix or a data.frame or the like:
> > m <- matrix(ncol=3,seq(1,9))
> > m
>      [,1] [,2] [,3]
> [1,]    1    4    7
> [2,]    2    5    8
> [3,]    3    6    9
>
> and now I wonder if one can provide somehow two vectors, one containing
> row numbers, the other column numbers and thereby retrieve the
> corresponding elements?
> E.g., providing the 2 vectors c(1,2,3) and c(1,3,1) should return the
> matrix values c(1,8,3).
>
> I ran a couple of times into this problem and always used some awkward
> transformations to get around it.
> But as I know R, there is probably some slick way to do this.
>
> Thanks!!!
>   Werner
>
>
>
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.







More information about the R-help mailing list