Re: [R] Extracting from a matrix w/o for-loop

From: Liaw, Andy <andy_liaw_at_merck.com>
Date: Sat 29 Jul 2006 - 02:44:11 EST


Yes, by matrix indexing:

R> M1[M2]
[1] 1 2 13 15 8
R> v
[1] 1 2 13 15 8

Andy

From: Camarda, Carlo Giovanni
>
> Dear R-users,
>
> likely there is a simple solution for this problem, but I currently
> cannot see it.
>
> I basically would like to get from a matrix values in particular
> positions which are the rows of another matrix, without using a
> for-loop.
>
> In other words: is there any way to avoid the for-loop in the
> following
> simple example:
>
> M1 <- matrix(1:20, ncol=2)
> M2 <- rbind(c(1,1), c(2,1), c(3,2), c(5,2), c(8,1))
> v <- numeric(nrow(M2))
> for(i in 1:length(v)){
> v[i] <- M1[M2[i,1], M2[i,2]]
> }
>
> Any suggestion would be welcome,
>
> Ciao,
> Carlo Giovanni Camarda
>
> ===========================================
> Camarda Carlo Giovanni
> PhD-Student
> Max Planck Institute for Demographic Research
> Konrad-Zuse-Strasse 1
> 18057 Rostock, Germany
> Tel: +49 (0)381 2081 172
> Fax: +49 (0)381 2081 472
> camarda@demogr.mpg.de
> ===========================================
>
>
> ----------
> This mail has been sent through the MPI for Demographic
> Rese...{{dropped}}
>
> ______________________________________________
> R-help@stat.math.ethz.ch 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.
>
>



R-help@stat.math.ethz.ch 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. Received on Sat Jul 29 02:50:26 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sat 29 Jul 2006 - 04:16:59 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.