# [R] Getting elements of a matrix by a vector of column indice s

Wolfram Fischer wolfram at fischer-zim.ch
Thu Jul 8 16:26:00 CEST 2004

```Thanks for you answer! It works.

>	m <- outer(letters[1:5], 1:4, paste, sep="")

The following works with the help of your proposition:
>	rowidx.n <- c( 2, 3, 4)
>	colidx.n <- c( 1, 3, 2)
>	idx.n <- cbind( rowidx.n, colidx.n )
>	m[idx.n]
[1] "b1" "c3" "d2"

In my real data there was an additional difficulty:
I had names of rows and columns as indices:
>	rownames(m) <- paste('R', 1:nrow(m), sep="")
>	colnames(m) <- paste('C', 1:ncol(m), sep="" )

And the following did not work anymore:
>	rowidx <- c( 'R2', 'R3', 'R4' )
>	colidx <- c( 'C1', 'C3', 'C2' )
>	idx <- cbind( rowidx, colidx )
>	m[idx]
<NA> <NA> <NA> <NA> <NA> <NA>
NA   NA   NA   NA   NA   NA

Do you have another suggestion? - Thanks! Wolfram

--- In reply to: ---
>Date:    08.07.04 08:21 (-0400)
>From:    "Liaw, Andy" <andy_liaw at merck.com>
>Subject: RE: [R] Getting elements of a matrix by a vector of column indice s
>
> See if the following helps:
>
> > m <- outer(letters[1:5], 1:4, paste, sep="")
> > m
>      [,1] [,2] [,3] [,4]
> [1,] "a1" "a2" "a3" "a4"
> [2,] "b1" "b2" "b3" "b4"
> [3,] "c1" "c2" "c3" "c4"
> [4,] "d1" "d2" "d3" "d4"
> [5,] "e1" "e2" "e3" "e4"
> > idx <- c(2, 1, 3, 4, 2)
> > m[cbind(1:5, idx)]
> [1] "a2" "b1" "c3" "d4" "e2"
>
> Andy
>
> > From: Wolfram Fischer
> >
> > I have e.g.
> >     t <- matrix( nrow=2, ncol=3, byrow=TRUE,
> > c('a1','a2','a3','b1','b2','b3') )
> > and
> >     i <- c( 3, 2)
> >
> > Is it possible to formulate a simple expression that gets
> >     c( t[ 1, i[1] ], t[ 2, i[2] ] )
> > (and so on for longer matrices)?
> >
> > The result would be:
> >     [1] "a3" "b2"
> >
> > Thanks - Wolfram
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide!
> > http://www.R-project.org/posting-guide.html
> >
> >
>
>
> ------------------------------------------------------------------------------
> Notice:  This e-mail message, together with any attachments, contains information of Merck & Co., Inc. (One Merck Drive, Whitehouse Station, New Jersey, USA 08889), and/or its affiliates (which may be known outside the United States as Merck Frosst, Merck Sharp & Dohme or MSD and in Japan, as Banyu) that may be confidential, proprietary copyrighted and/or legally privileged. It is intended solely for the use of the individual or entity named on this message.  If you are not the intended recipient, and have received this message in error, please notify us immediately by reply e-mail and then delete it from your system.
> ------------------------------------------------------------------------------

```

More information about the R-help mailing list