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

Greg Snow Greg.Snow at imail.org
Wed Oct 22 20:37:28 CEST 2008


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